#include <stdio.h>
#include <errno.h>
#include <getopt.h>
#include <stdlib.h> /* free, exit */

#include <string.h> /* strdup */

#include <pcap.h>

#include <net/ethernet.h> /* struct ethhdr */

#include <sys/socket.h> /* inet_ntoa */
#include <netinet/in.h> /* IPPROTO_TCP ... */
#include <arpa/inet.h>

#include <linux/ip.h> /* struct iphdr */

#include "main.h"
#include "pcap_ip.h"
#include "pcap_tcp.h"
#include "pcap_udp.h"

struct in_addr get_ipsaddr(const u_char *packet)
{
	struct iphdr* ip;
	struct in_addr* addr;

	ip = (struct iphdr*)(packet + sizeof(struct ethhdr));
	addr = (struct in_addr*)&(ip->saddr);
	DEBUGP(D_NOTICE, "saddr: %s\n", inet_ntoa(*addr));
	return *addr;
}

struct in_addr get_ipdaddr(const u_char *packet)
{
	struct iphdr* ip;
	struct in_addr* addr;

	ip = (struct iphdr*)(packet + sizeof(struct ethhdr));
	addr = (struct in_addr*)&(ip->daddr);
	DEBUGP(D_NOTICE, "daddr: %s\n", inet_ntoa(*addr));
	return *addr;
}

void handle_ip(const u_char *packet)
{
	char *saddr, *daddr;
	struct iphdr *ip;

	ip = (struct iphdr*)(packet + sizeof(struct ethhdr));

	switch (ip->protocol) {
	case IPPROTO_TCP:
		DEBUGP(D_NOTICE, "TCP/IP packet!\n");
		handle_tcp(packet);
	break;

	case IPPROTO_UDP:
		DEBUGP(D_NOTICE, "UDP/IP packet!\n");
		handle_udp(packet);
	break;

	case IPPROTO_ICMP:
		DEBUGP(D_NOTICE, "ICMP packet!\n");
	break;

	default:
		saddr = strdup(inet_ntoa(get_ipsaddr(packet)));
		daddr = strdup(inet_ntoa(get_ipdaddr(packet)));

		DEBUGP(D_WARNING, "IP protocol:%d, from:%s, to:%s\n",
				ip->protocol,
				saddr, daddr);

		free(saddr);
		free(daddr);
	break;
	}
}


