#include "CPacket.h"
#include <netinet/in.h>

CRefPtr <const CPacket> CPacket::scanPacket(const unsigned char* buffer)
{
	CPacket* p = new CPacket;

	unsigned long *addr_packet_id;
	unsigned long *addr_arrived;
	unsigned short int *addr_len;
	unsigned long int *addr_ip_src;
	unsigned long int *addr_ip_dst;
	unsigned char *addr_protocol;
	unsigned short int *addr_port_src; 
	unsigned short int *addr_port_dst; 
	unsigned short int *addr_tcp_flags;
	unsigned char *addr_icmp_type;
	unsigned char *addr_hook;	
	unsigned char *addr_mac_addrlen;


	addr_packet_id = (unsigned long *) (buffer +0);
	addr_arrived = (unsigned long *) (buffer +4);
	addr_len = (unsigned short *) (buffer +8);
	addr_ip_src = (unsigned long *) (buffer +10);
	addr_ip_dst = (unsigned long *) (buffer +14);
	addr_protocol = (unsigned char *) (buffer +18);
	addr_port_src = (unsigned short *) (buffer +19);
	addr_port_dst = (unsigned short *) (buffer +21);
	addr_tcp_flags = (unsigned short *) (buffer +23);
	addr_icmp_type = (unsigned char *) (buffer +25);
	addr_hook = (unsigned char *) (buffer +26);
	addr_mac_addrlen = (unsigned char *) (buffer +27);


	// unsigned long packet_id;
	p->packet_id = ntohl( *addr_packet_id );

	// unsigned long arrived;
	p->arrived = ntohl( *addr_arrived );

	// unsigned short int len;
	p->len = ntohs( *addr_len );

	// unsigned long ip_src; could be char[4]: no ntohl.
	p->ip_src = *addr_ip_src;

	// unsigned long ip_dst; could be char[4]: no ntohl.
	p->ip_dst = *addr_ip_dst;

 	// unsigned int protocol:8;
	// original protocol type is char....
	p->protocol = *addr_protocol;
	
	// unsigned short int port_src;
	p->port_src = ntohs( *addr_port_src );

	// unsigned short int port_dst;
	p->port_dst = ntohs( *addr_port_dst );

	// unsigned short int tcp_flags;
	p->tcp_flags = ntohs(*addr_tcp_flags );

	// unsigned int icmp_type:8;
	p->icmp_type = *addr_icmp_type;
	
	// unsigned int hook;
	// WARNING used first byte only!
	p->hook = buffer[26];
	
	// unsigned int mac_addrlen:8;
	p->mac_addrlen = *addr_mac_addrlen;
	// unsigned char mac_addr[8];
	memcpy(p->mac_addr, (char*)buffer+28, 8);
	
	// unsigned char interface_in[IFNAMSIZ];
	// unsigned char interface_out[IFNAMSIZ];
	memcpy(p->interface_in, (char*)buffer+36, IFNAMSIZ);
	memcpy(p->interface_out, (char*)buffer+36+IFNAMSIZ, IFNAMSIZ);
	
	if (buffer[36+2*IFNAMSIZ] > 0)
		p->programname = (char*) buffer+36+2*IFNAMSIZ+1;
	else
		//p->programname.clear();
		p->programname = "";

	return p;
}
