//Jianzhong Fang @ Endace ! Aug 2007

#include <sys/types.h>
#if defined(__FreeBSD__) || defined(__linux__) || (defined(__SVR4) && defined(__sun)) || (defined(__APPLE__) && defined(__ppc__))
#include <netinet/in.h>
#elif defined(_WIN32)
#include <wintypedefs.h>
#endif
#include <stdio.h>
#include "xpack.h"

void print_eth_hd(void *a)
{
  char *p;
  int   i;
  
  p = (char*)a;
  printf("Ether HD\n");

  for (i=5; i>=0; i--) printf("%02x ", *(p+i));
  printf(" : ");
  for (i=11; i>=6; i--) printf("%02x ", *(p+i));

  printf("\n%04x\n", ntohs(*(short*)(p+12)));
}

void print_ip_hd(void *a)
{
  struct pack_ipnet *p;

  p = (struct pack_ipnet *)a;

  printf("IP HD\n");
  printf("ip_vhl:%02x\n", p->ip_vhl);               //1B version & header
  printf("ip_tos:%02x\n", p->ip_tos);               //1B type of service
  printf("ip_len:%04x\n", ntohs(p->ip_len));        //2B total length
  printf("ip_id:%04x\n", ntohs(p->ip_id));          //2B identification
  printf("ip_off:%04x\n", ntohs(p->ip_off));        //2B fragment offset field
  printf("ip_ttl:%02x\n", p->ip_ttl);               //1B time to live
  printf("ip_p:%02x\n", p->ip_p);                   //1B protocol
  printf("ip_sum:%04x\n", p->ip_sum);               //2B checksum
  printf("ip_src:%08x\n", ntohl(p->ip_src.s_addr)); //4B source addr
  printf("ip_dst:%08x\n", ntohl(p->ip_dst.s_addr)); //4B destination addr
}

void print_tcp_hd(void *a)
{
  struct pack_ipnet *aa;
  struct pack_tcpnet *p;

  aa = (struct pack_ipnet *)a;
  p = (struct pack_tcpnet *)((char *)a+IP_HSZ(aa));

  printf("tcp_sport:%04x\n", ntohs(p->tcp_sport));   //2B source port
  printf("tcp_dport:%04x\n", ntohs(p->tcp_dport));   //2B destination port
  printf("tcp_seq:%08x\n", ntohl(p->tcp_seq));       //4B sequence number
  printf("tcp_ack:%08x\n", ntohl(p->tcp_ack));       //4B acknowledge number
  printf("tcp_off4x:%02x\n", p->tcp_off4x);          //1BH TCP header number

  printf("tcp_flag:%02x\n", p->tcp_flag);            //1B:: C E U A P R S F
  printf("tcp_win:%04x\n", ntohs(p->tcp_win));       //2B
  printf("tcp_sum:%04x\n", ntohs(p->tcp_sum));       //2B
  printf("tcp_uptr:%04x\n", ntohs(p->tcp_uptr));     //2B urgent pointer
}


unsigned short CHKSUMIP(struct pack_ipnet *ip)
{
  short len;
  unsigned short *p;
  int   sum = 0;

  len = IP_HSZ(ip);
  printf("len: %04x\n", len);
  p = (unsigned short *)ip;

  while(len > 1){
    sum += *p++;
    if(sum & 0x80000000)   /* if high order bit set, fold */
      sum = (sum & 0xFFFF) + (sum >> 16);
    len -= 2;
  }

  if(len)       /* take care of left over byte */
    sum += (unsigned short) *(unsigned char *)p;

  while(sum>>16)
    sum = (sum & 0xFFFF) + (sum >> 16);

  return sum;
}
