Packet Sniffer Code in C using Winsock

Introduction
Ever since windows 2000/XP when IP_HDRINCL became a valid option for setsockopt() , WSAIoctl() had another option called SIO_RCVALL which enabled a raw socket to sniff all incoming traffic over the selected interface to whose IP the socket was bound.Hence to make a sniffer in Winsock he simple steps are :



1. Create a raw socket.
2. Bind the socket to the local IP over which the traffic is to be sniffed.
3. WSAIoctl() the socket with SIO_RCVALL to give it sniffing powers.
4. Put the socket in an infinite loop of recvfrom.
5. n’ joy! the Buffer from recvfrom.

Now this feature of winsock is available on all 2000/XP and higher windows. But there are few drawbacks.

1. Ethernet header is not available in winsock sniffing.
2. Only incoming data is sniffed on XP and XP+SP1.
3. Both incoming and outgoing data is sniffed on XP+SP1+SP2. (actual behavior may vary).

Few more effects might be visible like :

1. Outgoing UDP and ICMP packets are not captured.
2. On Windows Vista with SP1, only UDP packets are captured. TCP packets are not captured at all.

I have not checked higher versions of windows. Moreover non IP packets (e.g. ARP) may not be captured at all.
So if full fledged sniffing is required then packet drivers like winpcap should help.

In the following source code all packets are assumed to be IP packets. VC++ 6.0 on Win XP used here.

Code


SOCKET sniffer = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
bind(sniffer,(struct sockaddr *)&dest,sizeof(dest))
dest must have the details as follows :

memcpy(&dest.sin_addr.s_addr,local->h_addr_list[in],
sizeof(dest.sin_addr.s_addr));
dest.sin_family = AF_INET;
dest.sin_port = 0;
dest.sin_zero = 0;


where HOSTENT *local should have the local IPs

WSAIoctl(sniffer, SIO_RCVALL, &j, sizeof(j), 0, 0, &in,0, 0);

where j must be 1 and in can be any integer

while(1)
{
 recvfrom(sniffer,Buffer,65536,0,0,0); //ring-a-ring-a roses
}

To get the local IP’s associated with the machine all that needs to be done
is:

gethostname(hostname, sizeof(hostname); //its a char hostname[100] for local hostname
HOSTENT *local = gethostbyname(hostname); //now local will have all local ips

Now socket sniffer will receive all incoming packets along with their headers
and all that will be stored in the Buffer.After that some typecasting with
structures representing the headers will help.

typedef struct ip_hdr
{
 unsigned char  ip_header_len:4;  // 4-bit header length (in 32-bit words)
 unsigned char  ip_version   :4;  // 4-bit IPv4 version
 unsigned char  ip_tos;           // IP type of service
 unsigned short ip_total_length;  // Total length
 unsigned short ip_id;            // Unique identifier

 unsigned char  ip_frag_offset   :5; // Fragment offset field

 unsigned char  ip_more_fragment :1;
 unsigned char  ip_dont_fragment :1;
 unsigned char  ip_reserved_zero :1;

 unsigned char  ip_frag_offset1;    //fragment offset

 unsigned char  ip_ttl;           // Time to live
 unsigned char  ip_protocol;      // Protocol(TCP,UDP etc)
 unsigned short ip_checksum;      // IP checksum
 unsigned int   ip_srcaddr;       // Source address
 unsigned int   ip_destaddr;      // Source address
}   IPV4_HDR;

typedef struct udp_hdr
{
 unsigned short source_port;     // Source port no.
 unsigned short dest_port;       // Dest. port no.
 unsigned short udp_length;      // Udp packet length
 unsigned short udp_checksum;    // Udp checksum (optional)
}   UDP_HDR;

typedef struct tcp_header
{
 unsigned short source_port;  // source port
 unsigned short dest_port;    // destination port
 unsigned int   sequence;     // sequence number - 32 bits
 unsigned int   acknowledge;  // acknowledgement number - 32 bits

 unsigned char  ns   :1;          //Nonce Sum Flag Added in RFC 3540.
 unsigned char  reserved_part1:3; //according to rfc
 unsigned char  data_offset:4;    //number of dwords in the TCP header.

 unsigned char  fin  :1;      //Finish Flag
 unsigned char  syn  :1;      //Synchronise Flag
 unsigned char  rst  :1;      //Reset Flag
 unsigned char  psh  :1;      //Push Flag
 unsigned char  ack  :1;      //Acknowledgement Flag
 unsigned char  urg  :1;      //Urgent Flag

 unsigned char  ecn  :1;      //ECN-Echo Flag
 unsigned char  cwr  :1;      //Congestion Window Reduced Flag

 unsigned short window;          // window
 unsigned short checksum;        // checksum
 unsigned short urgent_pointer;  // urgent pointer
}   TCP_HDR;

typedef struct icmp_hdr
{
 BYTE type;          // ICMP Error type
 BYTE code;          // Type sub code
 USHORT checksum;
 USHORT id;
 USHORT seq;
}   ICMP_HDR;



The ip_protocol field of the ip header determines the type of the packet; for
e.g 1 means a icmp packet and 2-igmp 6-tcp 17-udp and so on.RFC 1340 should help
more. Another function in the source code is PrintData() which prints the data
dumps in a hex view fashion as done by other sniffers and looks like this :

Output

The terminal will show the total packet count :


Initialising Winsock...Initialised
Creating RAW Socket...Created.
Host name : ----------

Available Network Interfaces :
Interface Number : 0 Address : 192.168.0.101
Enter the interface number you would like to sniff : 0

Binding socket to local system and port 0 ...Binding successful
Setting socket to sniff...Socket set.
Started Sniffing
Packet Capture Statistics...
TCP : 52 UDP : 2 ICMP : 0 IGMP : 0 Others : 0 Total : 54

The log file can look like this :

***********************TCP Packet*************************

IP Header
 |-IP Version : 4
 |-IP Header Length : 5 DWORDS or 20 Bytes
 |-Type Of Service : 0
 |-IP Total Length : 516 Bytes(Size of Packet)
 |-Identification : 36638
 |-Reserved ZERO Field : 0
 |-Dont Fragment Field : 0
 |-More Fragment Field : 0
 |-TTL : 53
 |-Protocol : 6
 |-Checksum : 65082
 |-Source IP : 74.125.235.16
 |-Destination IP : 192.168.0.101

TCP Header
 |-Source Port : 80
 |-Destination Port : 1071
 |-Sequence Number : 1844770279
 |-Acknowledge Number : 1324763201
 |-Header Length : 5 DWORDS or 20 BYTES
 |-CWR Flag : 0
 |-ECN Flag : 0
 |-Urgent Flag : 0
 |-Acknowledgement Flag : 1
 |-Push Flag : 1
 |-Reset Flag : 0
 |-Synchronise Flag : 0
 |-Finish Flag : 0
 |-Window : 107
 |-Checksum : 51478
 |-Urgent Pointer : 0

 DATA Dump 
IP Header
 45 00 02 04 8f 1e 00 00 35 06 fe 3a 4a 7d eb 10          E.......5..:J}.. 
 c0 a8 00 65                                              ...e 

TCP Header
 00 50 04 2f 6d f4 f5 e7 4e f6 48 41 50 18 00 6b          .P./m...N.HAP..k 
 c9 16 00 00                                              .... 

Data Payload
 48 54 54 50 2f 31 2e 31 20 33 30 32 20 46 6f 75          HTTP/1.1 302 Fou 
 6e 64 0d 0a 4c 6f 63 61 74 69 6f 6e 3a 20 68 74          nd..Location: ht 
 74 70 3a 2f 2f 77 77 77 2e 67 6f 6f 67 6c 65 2e          tp://www.google. 
 63 6f 2e 69 6e 2f 0d 0a 43 61 63 68 65 2d 43 6f          co.in/..Cache-Co 
 6e 74 72 6f 6c 3a 20 70 72 69 76 61 74 65 0d 0a          ntrol: private.. 
 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 65          Content-Type: te 
 78 74 2f 68 74 6d 6c 3b 20 63 68 61 72 73 65 74          xt/html; charset 
 3d 55 54 46 2d 38 0d 0a 44 61 74 65 3a 20 57 65          =UTF-8..Date: We 
 64 2c 20 31 34 20 44 65 63 20 32 30 31 31 20 30          d, 14 Dec 2011 0 
 39 3a 32 38 3a 33 39 20 47 4d 54 0d 0a 53 65 72          9:28:39 GMT..Ser 
 76 65 72 3a 20 67 77 73 0d 0a 43 6f 6e 74 65 6e          ver: gws..Conten 
 74 2d 4c 65 6e 67 74 68 3a 20 32 32 31 0d 0a 58          t-Length: 221..X 
 2d 58 53 53 2d 50 72 6f 74 65 63 74 69 6f 6e 3a          -XSS-Protection: 
 20 31 3b 20 6d 6f 64 65 3d 62 6c 6f 63 6b 0d 0a           1; mode=block.. 
 58 2d 46 72 61 6d 65 2d 4f 70 74 69 6f 6e 73 3a          X-Frame-Options: 
 20 53 41 4d 45 4f 52 49 47 49 4e 0d 0a 0d 0a 3c           SAMEORIGIN....< 
 48 54 4d 4c 3e 3c 48 45 41 44 3e 3c 6d 65 74 61          HTML><HEAD><meta 
 20 68 74 74 70 2d 65 71 75 69 76 3d 22 63 6f 6e           http-equiv="con 
 74 65 6e 74 2d 74 79 70 65 22 20 63 6f 6e 74 65          tent-type" conte 
 6e 74 3d 22 74 65 78 74 2f 68 74 6d 6c 3b 63 68          nt="text/html;ch 
 61 72 73 65 74 3d 75 74 66 2d 38 22 3e 0a 3c 54          arset=utf-8">.<T 
 49 54 4c 45 3e 33 30 32 20 4d 6f 76 65 64 3c 2f          ITLE>302 Moved</ 
 54 49 54 4c 45 3e 3c 2f 48 45 41 44 3e 3c 42 4f          TITLE></HEAD><BO 
 44 59 3e 0a 3c 48 31 3e 33 30 32 20 4d 6f 76 65          DY>.<H1>302 Move 
 64 3c 2f 48 31 3e 0a 54 68 65 20 64 6f 63 75 6d          d</H1>.The docum 
 65 6e 74 20 68 61 73 20 6d 6f 76 65 64 0a 3c 41          ent has moved.<A 
 20 48 52 45 46 3d 22 68 74 74 70 3a 2f 2f 77 77           HREF="http://ww 
 77 2e 67 6f 6f 67 6c 65 2e 63 6f 2e 69 6e 2f 22          w.google.co.in/" 
 3e 68 65 72 65 3c 2f 41 3e 2e 0d 0a 3c 2f 42 4f          >here</A>...</BO 
 44 59 3e 3c 2f 48 54 4d 4c 3e 0d 0a                      DY></HTML>.. 

To the right we only print the characters which are either an alphabet or a number. Everything is saved in a log file named log.txt.

Conclusion

The source code demonstrates simple concepts which can be used to develop a protocol analyzer like Ethereal.In the source code only tcp,udp and icmp packets have been broken into fields and that too according to normal situations.
Variations in packet structures (for e.g. in case of icmp) are there to which the program might give inaccurate results.So you have to develop the program in the relevant way and implement all necessary error checking algorithms etc.

Minor changes in the source code will adapt it to the winpcap environment so that everything on the wire can be sniffed!

Happy Sniffing!

Source Code :



/*
	Simple Sniffer in winsock
	Author : Silver Moon ( m00n.silv3r@gmail.com )
*/

#include "stdio.h"
#include "winsock2.h"

#pragma comment(lib,"ws2_32.lib") //For winsock

#define SIO_RCVALL _WSAIOW(IOC_VENDOR,1) //this removes the need of mstcpip.h

void StartSniffing (SOCKET Sock); //This will sniff here and there

void ProcessPacket (char* , int); //This will decide how to digest
void PrintIpHeader (char*);
void PrintIcmpPacket (char* , int);
void PrintUdpPacket (char* , int);
void PrintTcpPacket (char* , int);
void ConvertToHex (char* , unsigned int);
void PrintData (char* , int);

typedef struct ip_hdr
{
	unsigned char ip_header_len:4; // 4-bit header length (in 32-bit words) normally=5 (Means 20 Bytes may be 24 also)
	unsigned char ip_version :4; // 4-bit IPv4 version
	unsigned char ip_tos; // IP type of service
	unsigned short ip_total_length; // Total length
	unsigned short ip_id; // Unique identifier

	unsigned char ip_frag_offset :5; // Fragment offset field

	unsigned char ip_more_fragment :1;
	unsigned char ip_dont_fragment :1;
	unsigned char ip_reserved_zero :1;

	unsigned char ip_frag_offset1; //fragment offset

	unsigned char ip_ttl; // Time to live
	unsigned char ip_protocol; // Protocol(TCP,UDP etc)
	unsigned short ip_checksum; // IP checksum
	unsigned int ip_srcaddr; // Source address
	unsigned int ip_destaddr; // Source address
} IPV4_HDR;

typedef struct udp_hdr
{
	unsigned short source_port; // Source port no.
	unsigned short dest_port; // Dest. port no.
	unsigned short udp_length; // Udp packet length
	unsigned short udp_checksum; // Udp checksum (optional)
} UDP_HDR;

// TCP header
typedef struct tcp_header
{
	unsigned short source_port; // source port
	unsigned short dest_port; // destination port
	unsigned int sequence; // sequence number - 32 bits
	unsigned int acknowledge; // acknowledgement number - 32 bits

	unsigned char ns :1; //Nonce Sum Flag Added in RFC 3540.
	unsigned char reserved_part1:3; //according to rfc
	unsigned char data_offset:4; /*The number of 32-bit words in the TCP header.
	This indicates where the data begins.
	The length of the TCP header is always a multiple
	of 32 bits.*/

	unsigned char fin :1; //Finish Flag
	unsigned char syn :1; //Synchronise Flag
	unsigned char rst :1; //Reset Flag
	unsigned char psh :1; //Push Flag
	unsigned char ack :1; //Acknowledgement Flag
	unsigned char urg :1; //Urgent Flag

	unsigned char ecn :1; //ECN-Echo Flag
	unsigned char cwr :1; //Congestion Window Reduced Flag

	////////////////////////////////

	unsigned short window; // window
	unsigned short checksum; // checksum
	unsigned short urgent_pointer; // urgent pointer
} TCP_HDR;

typedef struct icmp_hdr
{
	BYTE type; // ICMP Error type
	BYTE code; // Type sub code
	USHORT checksum;
	USHORT id;
	USHORT seq;
} ICMP_HDR;

FILE *logfile;
int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;
struct sockaddr_in source,dest;
char hex[2];

//Its free!
IPV4_HDR *iphdr;
TCP_HDR *tcpheader;
UDP_HDR *udpheader;
ICMP_HDR *icmpheader;

int main()
{
	SOCKET sniffer;
	struct in_addr addr;
	int in;

	char hostname[100];
	struct hostent *local;
	WSADATA wsa;

	logfile=fopen("log.txt","w");
	if(logfile == NULL)
	{
		printf("Unable to create file.");
	}

	//Initialise Winsock
	printf("\nInitialising Winsock...");
	if (WSAStartup(MAKEWORD(2,2), &wsa) != 0)
	{
		printf("WSAStartup() failed.\n");
		return 1;
	}
	printf("Initialised");

	//Create a RAW Socket
	printf("\nCreating RAW Socket...");
	sniffer = socket(AF_INET, SOCK_RAW, IPPROTO_IP);
	if (sniffer == INVALID_SOCKET)
	{
		printf("Failed to create raw socket.\n");
		return 1;
	}
	printf("Created.");

	//Retrive the local hostname
	if (gethostname(hostname, sizeof(hostname)) == SOCKET_ERROR)
	{
		printf("Error : %d",WSAGetLastError());
		return 1;
	}
	printf("\nHost name : %s \n",hostname);

	//Retrive the available IPs of the local host
	local = gethostbyname(hostname);
	printf("\nAvailable Network Interfaces : \n");
	if (local == NULL)
	{
		printf("Error : %d.\n",WSAGetLastError());
		return 1;
	}

	for (i = 0; local->h_addr_list[i] != 0; ++i)
	{
		memcpy(&addr, local->h_addr_list[i], sizeof(struct in_addr));
		printf("Interface Number : %d Address : %s\n",i,inet_ntoa(addr));
	}

	printf("Enter the interface number you would like to sniff : ");
	scanf("%d",&in);

	memset(&dest, 0, sizeof(dest));
	memcpy(&dest.sin_addr.s_addr,local->h_addr_list[in],sizeof(dest.sin_addr.s_addr));
	dest.sin_family = AF_INET;
	dest.sin_port = 0;

	printf("\nBinding socket to local system and port 0 ...");
	if (bind(sniffer,(struct sockaddr *)&dest,sizeof(dest)) == SOCKET_ERROR)
	{
		printf("bind(%s) failed.\n", inet_ntoa(addr));
		return 1;
	}
	printf("Binding successful");

	//Enable this socket with the power to sniff : SIO_RCVALL is the key Receive ALL ;)

	j=1;
	printf("\nSetting socket to sniff...");
	if (WSAIoctl(sniffer, SIO_RCVALL, &j, sizeof(j), 0, 0, (LPDWORD) &in , 0 , 0) == SOCKET_ERROR)
	{
		printf("WSAIoctl() failed.\n");
		return 1;
	}
	printf("Socket set.");

	//Begin
	printf("\nStarted Sniffing\n");
	printf("Packet Capture Statistics...\n");
	StartSniffing(sniffer); //Happy Sniffing

	//End
	closesocket(sniffer);
	WSACleanup();

	return 0;
}

void StartSniffing(SOCKET sniffer)
{
	char *Buffer = (char *)malloc(65536); //Its Big!
	int mangobyte;

	if (Buffer == NULL)
	{
		printf("malloc() failed.\n");
		return;
	}

	do
	{
		mangobyte = recvfrom(sniffer , Buffer , 65536 , 0 , 0 , 0); //Eat as much as u can

		if(mangobyte > 0)
		{
			ProcessPacket(Buffer, mangobyte);
		}
		else
		{
			printf( "recvfrom() failed.\n");
		}
	}
	while (mangobyte > 0);

	free(Buffer);
}

void ProcessPacket(char* Buffer, int Size)
{
	iphdr = (IPV4_HDR *)Buffer;
	++total;

	switch (iphdr->ip_protocol) //Check the Protocol and do accordingly...
	{
		case 1: //ICMP Protocol
		++icmp;
		PrintIcmpPacket(Buffer,Size);
		break;

		case 2: //IGMP Protocol
		++igmp;
		break;

		case 6: //TCP Protocol
		++tcp;
		PrintTcpPacket(Buffer,Size);
		break;

		case 17: //UDP Protocol
		++udp;
		PrintUdpPacket(Buffer,Size);
		break;

		default: //Some Other Protocol like ARP etc.
		++others;
		break;
	}
	printf("TCP : %d UDP : %d ICMP : %d IGMP : %d Others : %d Total : %d\r",tcp,udp,icmp,igmp,others,total);
}

void PrintIpHeader (char* Buffer )
{
	unsigned short iphdrlen;

	iphdr = (IPV4_HDR *)Buffer;
	iphdrlen = iphdr->ip_header_len*4;

	memset(&source, 0, sizeof(source));
	source.sin_addr.s_addr = iphdr->ip_srcaddr;

	memset(&dest, 0, sizeof(dest));
	dest.sin_addr.s_addr = iphdr->ip_destaddr;

	fprintf(logfile,"\n");
	fprintf(logfile,"IP Header\n");
	fprintf(logfile," |-IP Version : %d\n",(unsigned int)iphdr->ip_version);
	fprintf(logfile," |-IP Header Length : %d DWORDS or %d Bytes\n",(unsigned int)iphdr->ip_header_len,((unsigned int)(iphdr->ip_header_len))*4);
	fprintf(logfile," |-Type Of Service : %d\n",(unsigned int)iphdr->ip_tos);
	fprintf(logfile," |-IP Total Length : %d Bytes(Size of Packet)\n",ntohs(iphdr->ip_total_length));
	fprintf(logfile," |-Identification : %d\n",ntohs(iphdr->ip_id));
	fprintf(logfile," |-Reserved ZERO Field : %d\n",(unsigned int)iphdr->ip_reserved_zero);
	fprintf(logfile," |-Dont Fragment Field : %d\n",(unsigned int)iphdr->ip_dont_fragment);
	fprintf(logfile," |-More Fragment Field : %d\n",(unsigned int)iphdr->ip_more_fragment);
	fprintf(logfile," |-TTL : %d\n",(unsigned int)iphdr->ip_ttl);
	fprintf(logfile," |-Protocol : %d\n",(unsigned int)iphdr->ip_protocol);
	fprintf(logfile," |-Checksum : %d\n",ntohs(iphdr->ip_checksum));
	fprintf(logfile," |-Source IP : %s\n",inet_ntoa(source.sin_addr));
	fprintf(logfile," |-Destination IP : %s\n",inet_ntoa(dest.sin_addr));
}

void PrintTcpPacket(char* Buffer, int Size)
{
	unsigned short iphdrlen;

	iphdr = (IPV4_HDR *)Buffer;
	iphdrlen = iphdr->ip_header_len*4;

	tcpheader=(TCP_HDR*)(Buffer+iphdrlen);

	fprintf(logfile,"\n\n***********************TCP Packet*************************\n");

	PrintIpHeader( Buffer );

	fprintf(logfile,"\n");
	fprintf(logfile,"TCP Header\n");
	fprintf(logfile," |-Source Port : %u\n",ntohs(tcpheader->source_port));
	fprintf(logfile," |-Destination Port : %u\n",ntohs(tcpheader->dest_port));
	fprintf(logfile," |-Sequence Number : %u\n",ntohl(tcpheader->sequence));
	fprintf(logfile," |-Acknowledge Number : %u\n",ntohl(tcpheader->acknowledge));
	fprintf(logfile," |-Header Length : %d DWORDS or %d BYTES\n"
	,(unsigned int)tcpheader->data_offset,(unsigned int)tcpheader->data_offset*4);
	fprintf(logfile," |-CWR Flag : %d\n",(unsigned int)tcpheader->cwr);
	fprintf(logfile," |-ECN Flag : %d\n",(unsigned int)tcpheader->ecn);
	fprintf(logfile," |-Urgent Flag : %d\n",(unsigned int)tcpheader->urg);
	fprintf(logfile," |-Acknowledgement Flag : %d\n",(unsigned int)tcpheader->ack);
	fprintf(logfile," |-Push Flag : %d\n",(unsigned int)tcpheader->psh);
	fprintf(logfile," |-Reset Flag : %d\n",(unsigned int)tcpheader->rst);
	fprintf(logfile," |-Synchronise Flag : %d\n",(unsigned int)tcpheader->syn);
	fprintf(logfile," |-Finish Flag : %d\n",(unsigned int)tcpheader->fin);
	fprintf(logfile," |-Window : %d\n",ntohs(tcpheader->window));
	fprintf(logfile," |-Checksum : %d\n",ntohs(tcpheader->checksum));
	fprintf(logfile," |-Urgent Pointer : %d\n",tcpheader->urgent_pointer);
	fprintf(logfile,"\n");
	fprintf(logfile," DATA Dump ");
	fprintf(logfile,"\n");

	fprintf(logfile,"IP Header\n");
	PrintData(Buffer,iphdrlen);

	fprintf(logfile,"TCP Header\n");
	PrintData(Buffer+iphdrlen,tcpheader->data_offset*4);

	fprintf(logfile,"Data Payload\n");
	PrintData(Buffer+iphdrlen+tcpheader->data_offset*4
	,(Size-tcpheader->data_offset*4-iphdr->ip_header_len*4));

	fprintf(logfile,"\n###########################################################");
}

void PrintUdpPacket(char *Buffer,int Size)
{
	unsigned short iphdrlen;

	iphdr = (IPV4_HDR *)Buffer;
	iphdrlen = iphdr->ip_header_len*4;

	udpheader = (UDP_HDR *)(Buffer + iphdrlen);

	fprintf(logfile,"\n\n***********************UDP Packet*************************\n");

	PrintIpHeader(Buffer);

	fprintf(logfile,"\nUDP Header\n");
	fprintf(logfile," |-Source Port : %d\n",ntohs(udpheader->source_port));
	fprintf(logfile," |-Destination Port : %d\n",ntohs(udpheader->dest_port));
	fprintf(logfile," |-UDP Length : %d\n",ntohs(udpheader->udp_length));
	fprintf(logfile," |-UDP Checksum : %d\n",ntohs(udpheader->udp_checksum));

	fprintf(logfile,"\n");
	fprintf(logfile,"IP Header\n");

	PrintData(Buffer,iphdrlen);

	fprintf(logfile,"UDP Header\n");

	PrintData(Buffer+iphdrlen,sizeof(UDP_HDR));

	fprintf(logfile,"Data Payload\n");

	PrintData(Buffer+iphdrlen+sizeof(UDP_HDR) ,(Size - sizeof(UDP_HDR) - iphdr->ip_header_len*4));

	fprintf(logfile,"\n###########################################################");
}

void PrintIcmpPacket(char* Buffer , int Size)
{
	unsigned short iphdrlen;

	iphdr = (IPV4_HDR *)Buffer;
	iphdrlen = iphdr->ip_header_len*4;

	icmpheader=(ICMP_HDR*)(Buffer+iphdrlen);

	fprintf(logfile,"\n\n***********************ICMP Packet*************************\n");
	PrintIpHeader(Buffer);

	fprintf(logfile,"\n");

	fprintf(logfile,"ICMP Header\n");
	fprintf(logfile," |-Type : %d",(unsigned int)(icmpheader->type));

	if((unsigned int)(icmpheader->type)==11)
	{
		fprintf(logfile," (TTL Expired)\n");
	}
	else if((unsigned int)(icmpheader->type)==0)
	{
		fprintf(logfile," (ICMP Echo Reply)\n");
	}

	fprintf(logfile," |-Code : %d\n",(unsigned int)(icmpheader->code));
	fprintf(logfile," |-Checksum : %d\n",ntohs(icmpheader->checksum));
	fprintf(logfile," |-ID : %d\n",ntohs(icmpheader->id));
	fprintf(logfile," |-Sequence : %d\n",ntohs(icmpheader->seq));
	fprintf(logfile,"\n");

	fprintf(logfile,"IP Header\n");
	PrintData(Buffer,iphdrlen);

	fprintf(logfile,"UDP Header\n");
	PrintData(Buffer+iphdrlen,sizeof(ICMP_HDR));

	fprintf(logfile,"Data Payload\n");
	PrintData(Buffer+iphdrlen+sizeof(ICMP_HDR) , (Size - sizeof(ICMP_HDR) - iphdr->ip_header_len*4));

	fprintf(logfile,"\n###########################################################");
}

/*
	Print the hex values of the data
*/
void PrintData (char* data , int Size)
{
	char a , line[17] , c;
	int j;

	//loop over each character and print
	for(i=0 ; i < Size ; i++)
	{
		c = data[i];

		//Print the hex value for every character , with a space. Important to make unsigned
		fprintf(logfile," %.2x", (unsigned char) c);

		//Add the character to data line. Important to make unsigned
		a = ( c >=32 && c <=128) ? (unsigned char) c : '.';

		line[i%16] = a;

		//if last character of a line , then print the line - 16 characters in 1 line
		if( (i!=0 && (i+1)%16==0) || i == Size - 1)
		{
			line[i%16 + 1] = '\0';

			//print a big gap of 10 characters between hex and characters
			fprintf(logfile ,"          ");

			//Print additional spaces for last lines which might be less than 16 characters in length
			for( j = strlen(line) ; j < 16; j++)
			{
				fprintf(logfile , "   ");
			}

			fprintf(logfile , "%s \n" , line);
		}
	}

	fprintf(logfile , "\n");
}

Download the demo :
Sniffer Demo

Last Updated On : 7th August 2012

Related Posts

About the Author: Silver Moon

Php developer, blogger and Linux enthusiast. He can be reached at m00n.silv3r[at]gmail[dot]com
Click to know more.

  • Begin

    I compiler but it error

    undefined reference to ‘WSAStartup@8′

    undefined reference to ‘socket@12′

    undefined reference to ‘gethostname@8′

  • Nic Cha

    Cannot get the incoming packet on x86 win7.

    • Samuel Viveiros

      Disable the firewall ;)

  • Samuel Viveiros

    Hello,

    nice article.

    sorry, but I couldn’t resist. I did a version of the your code in Delphi:

    http://www.4shared.com/rar/zclnBD9a/SimpleSniffer-Delphi.html

    sorry my english :)

  • hind osman

    i want to write acode to reconfigration the router to work as firewall,can i do that in windows or only linux ,can you help me plzzzzzzzzz

    • Binary Tides

      router and firewalls are different things. routers have inbuilt firewall.
      provide more information on what you are trying to implement.

  • Ebrahim

    I compiled the code using Microsoft visual C++ Express Edition. I got these errors.

    1) line (184): error C2664: ‘WSAIoctl’ : cannot convert parameter 7 from ‘int *’ to ‘LPDWORD’

    2) line (205): error C2440: ‘initializing’ : cannot convert from ‘char *’ to ‘unsigned char *’

    3) line (216): error C2664: ‘recvfrom’ : cannot convert parameter 2 from ‘unsigned char *’ to ‘char *’

    4) line (453): error C2664: ‘strlen’ : cannot convert parameter 1 from ‘unsigned char [17]‘ to ‘const char *’

    • Binary Tides

      the code has been fixed.
      however these are actually warnings instead of errors , try reducing the warning level in vc++ project settings.

  • TheOtherGuy

    I tried to compile the code, and didn’t work.

    at line 114: it says log undeclared(first use in this function)

    Is there something im doing wrong?

    • Binary Tides

      code has been fixed. should compile without any errors.

  • Its me

    To sniff the ethernet header and its fields a packet sniffing library like winpcap can be used.

  • matoust

    I have tested the code and it works great. I would also like to be able to display the whole packet including the Ethernet frame (preamble, MAC dest. , MAC source and soon).

    Do you know ho to configure the port to get the whole package?

    Thanks
    Tomas Matousek

    • Binary Tides

      Ethernet header is not available with winsock.
      Winpcap library can be used. It provides the whole packet including the ethernet header.

  • Bool

    hi there, this article was of great help :D, i’m just playing around with Ragnarok Online (an MMORPG) and thanks to this I made a custom message logger, but I have got a problem.

    Today I tried to open the program in a Windows Vista machine, and it didn’t logged anything, I recompiled it with some printfs in several parts of the code just to know where the program was not working and I noticed it was not reaching this if

    void ProcessPacket(unsigned char* Buffer, int Size)
    {
    iphdr = (IPV4_HDR *)Buffer;
    if(iphdr->ip_protocol==6){
    InterceptPacket(Buffer,Size);
    }

    }

    it only checks if it is tcp because those are the packets I’m interested on, but I think the problem is that the machine could probably be using ipv6, so, my question is, how different are ipv6 headers and how can I distinguish ipv6 from ipv4?

    thanks for yout time

    • Binary Tides

      yes ipv6 headers are different from ipv4 headers.
      the ethernet header “protocol” field has to be checked to identify whether packet is ipv4 or ipv6. ipv4 has protocol number 0×0800 whereas ipv6 has protocol number 0x86DD. Full list here :

      http://www.iana.org/assignments/ethernet-numbers

      but winsock sniffer will not provide the ethernet header. winpcap has to be used.