#include <stdio.h>
#include <netinet/ip.h>
#include <netinet/ip_icmp.h>
#include <pcap.h>
#include <linux/if_ether.h>
#define	__FAVOR_BSD
#include <netinet/tcp.h>

#define DEFAULT_SNAPLEN 1500


char ebuf[PCAP_ERRBUF_SIZE];

void print_it(u_char *user, const struct pcap_pkthdr *h, const u_char *p){
  struct ethhdr	*eth = (struct ethhdr *)p;
  struct ip    	*ip;
  struct tcphdr	*tcp;
  unsigned char	*buff;
  int         	j,i = sizeof(struct ethhdr);

  printf("Total size (-14): %u\n",h->len-14);
  ip = (struct ip *)(p+i);
  buff = (unsigned char*)(p+i);
  i += (ip->ip_hl<<2);
  tcp = (struct tcphdr *)(p+i);
  printf("ip->ip_hl:			%#x\n",ip->ip_hl);
  printf("ip->ip_v:			%#x\n",ip->ip_v);
  printf("ip->ip_tos:			%#x\n",ip->ip_tos);
  printf("htons(ip->ip_len):		%#u\n",htons(ip->ip_len));
  printf("htons(ip->ip_id):		%#x\n",htons(ip->ip_id));
  printf("htons(ip->ip_off):		%#x\n",htons(ip->ip_off));
  printf("ip->ip_ttl:			%#x\n",ip->ip_ttl);
  printf("ip->ip_p:			%#x\n",ip->ip_p);
  printf("htons(ip->ip_sum):		%#x\n",htons(ip->ip_sum));
  printf("htonl(ip->ip_src.s_addr):	%#x\n",htonl(ip->ip_src.s_addr));
  printf("htonl(ip->ip_dst.s_addr):	%#x\n",htonl(ip->ip_dst.s_addr));
  printf("\n"); 
  printf("htons(tcp->th_sport):		%#x\n",htons(tcp->th_sport));
  printf("htons(tcp->th_dport):		%#x\n",htons(tcp->th_dport));
  printf("htonl(tcp->th_seq):		%#x\n",htonl(tcp->th_seq));
  printf("htonl(tcp->th_ack):		%#x\n",htonl(tcp->th_ack));
  printf("tcp->th_x2:			%#x\n",tcp->th_x2);
  printf("tcp->th_off:			%#x\n",tcp->th_off);
  printf("tcp->th_flags:			%#x\n",tcp->th_flags);
  printf("htons(tcp->th_win):		%#x\n",htons(tcp->th_win));
  printf("htons(tcp->th_sum):		%#x\n",htons(tcp->th_sum));
  printf("htons(tcp->th_urp):		%#x\n",htons(tcp->th_urp));
 
  for(j=0;j<htons(ip->ip_len);j+=2){
    printf("%c%.2x%.2x",j%16?' ':'\n',buff[j],buff[j+1]);
  }
  printf("\n");
  fflush(stdout);
}

int main(){
  int            snaplen = DEFAULT_SNAPLEN;
  char           *device = pcap_lookupdev(ebuf);
  pcap_t         *pd     = pcap_open_live("eth0", snaplen, 1, 1000, ebuf);
  bpf_u_int32    localnet, netmask;
  struct         bpf_program fcode;
  pcap_handler   printer;
  
  pcap_lookupnet("eth0", &localnet, &netmask, ebuf);

  printf("\033[0;37m\n"); 
 
  pcap_compile(pd, &fcode, "ip and tcp and dst 10.1.1.2", 1, netmask);

  pcap_setfilter(pd, &fcode);

  printer = print_it;

  pcap_loop(pd, 0, printer, 0);

  fflush(stdout);
  return 0;
}
