How to code a Packet Sniffer in C using Winsock

By | July 31, 2020

Winsock packet sniffer

A packet sniffer is a program that can sniff the packets moving on the network. All applications communicate over the network with data packets where each packet contains part of the whole data being exchanged.

A sniffer is able to pickup these individual packets and read them.

In this post we are going to write a very simple packet sniffer using sockets with the winsock api on windows.

Sniffing in Winsock

Since windows 2000, the winsock api got some features that allowed it to sniff packets moving in and out the network interface.

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. Call WSAIoctl() on the socket with SIO_RCVALL option to give it sniffing powers.
4. Put the socket in an infinite loop of recvfrom.
5. recvfrom gets the packet in the string buffer.

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

First create a raw socket and bind it to a local interface.

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 local is a HOSTENT pointer that contains the list of local ip addresses.

Next call WSAIoctl on the socket

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

where j must be 1 and in can be any integer

Now the final recvfrom loop to sniff data on the socket.

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. To extract various headers from the packet like IP header, tcp header etc, we need some structures.

Here is the code for the ip, tcp, udp and icmp headers

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 :

Download source code

Source Code on Github
Source as C file

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!

Download the compiled program here
Sniffer Demo

About Silver Moon

A Tech Enthusiast, Blogger, Linux Fan and a Software Developer. Writes about Computer hardware, Linux and Open Source software and coding in Python, Php and Javascript. He can be reached at [email protected].

21 Comments

How to code a Packet Sniffer in C using Winsock
  1. Brian

    May want to add a note – newer versions of Windows require “Run as Admin” to open a raw socket. Great basic tips, though!

  2. qandool

    Thanks for nice coding, i wand to add one more function to this code, a filter (let the user to see log of only tcp or udp packets). can someone help me please. thanks.

  3. SZM

    thank you for your nice coding, how can I add a filter to this code, so user may select type packet(s) (eg only Tcp or udp) and run the program. can someone help me. thanks as advanced.

  4. Begin

    I compiler but it error

    undefined reference to ‘WSAStartup@8’

    undefined reference to ‘socket@12’

    undefined reference to ‘gethostname@8’

  5. 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

    1. Binary Tides Post author

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

  6. 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 *’

    1. Binary Tides Post author

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

  7. 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?

  8. 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

    1. Binary Tides Post author

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

  9. 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

    1. Binary Tides Post author

      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 0x0800 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.

    2. Roby

      Hy, the program works great, i am on Windows 7 SP1 , u only need to change the property of the exe file to Compatible with Windows XP SP2.U will have a really nice log file with all the packets.This programmer did a really great job.

Leave a Reply

Your email address will not be published. Required fields are marked *