Click here to Skip to main content
15,355,133 members
Articles / Programming Languages / C#
Posted 5 Jan 2007


334 bookmarked

A Network Sniffer in C#

Rate me:
Please Sign up or sign in to vote.
4.87/5 (76 votes)
11 Feb 2008CPOL2 min read
A simple network sniffer which can parse IP, TCP, UDP, and DNS packets.
Sample Image - CSNetworkSniffer.jpg


In this article, I will discuss the working of a simple network sniffer which can parse IP, TCP, UDP, and DNS packets.

Capturing the Packets

// For sniffing the socket to capture the packets 
// has to be a raw socket, with the address family
// being of type internetwork, and protocol being IP
mainSocket = newSocket(AddressFamily.InterNetwork, SocketType.Raw,

// Bind the socket to the selected IP address

// Set the socket options
mainSocket.SetSocketOption(SocketOptionLevel.IP,  //Applies only to IP packets
                           SocketOptionName.HeaderIncluded, //Set the include header
                           true);                           //option to true

byte[] byTrue = newbyte[4]{1, 0, 0, 0};
byte[] byOut = newbyte[4];

//Socket.IOControl is analogous to the WSAIoctl method of Winsock 2
mainSocket.IOControl(IOControlCode.ReceiveAll,  //SIO_RCVALL of Winsock
                     byTrue, byOut);

//Start receiving the packets asynchronously
mainSocket.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None,
                        newAsyncCallback(OnReceive), null);

For capturing the packets, we use a raw socket and bind it to the IP address. After setting the proper options for the socket, we then call the IOControl method on it. Notice that IOControl is analogous to the Winsock2WSAIoctl method. The IOControlCode.ReceiveAll implies that all incoming and outgoing packets on the particular interface be captured.

The second parameter passed to IOControl with IOControlCode.ReceiveAll should be TRUE so an array byTrue is created and passed to it (thanks to Leonid Molochniy for this). Next we start receiving all packets asynchronously.

Analysing the Packets

The IP datagram encapsulates the TCP and UDP packets. This further contains the data sent by the application layer protocols such as DNS, HTTP, FTP, SMTP, SIP, etc. Thus a TCP packet is received inside the IP datagram, like this:

| IP header | TCP header |        Data        |  

So the first thing that we need to do is to parse the IP header. The stripped version of the IP header class is shown below, the comments describe the things as they happen.

public classIPHeader 
  //IP Header fields 
  private byte byVersionAndHeaderLength; // Eight bits for version and header 
                                         // length 
  private byte byDifferentiatedServices; // Eight bits for differentiated 
                                         // services
  private ushort usTotalLength;          // Sixteen bits for total length 
  private ushort usIdentification;       // Sixteen bits for identification
  private ushort usFlagsAndOffset;       // Eight bits for flags and frag. 
                                         // offset 
  private byte byTTL;                    // Eight bits for TTL (Time To Live) 
  private byte byProtocol;               // Eight bits for the underlying 
                                         // protocol 
  private short sChecksum;               // Sixteen bits for checksum of the 
                                         //  header 
  private uint uiSourceIPAddress;        // Thirty two bit source IP Address 
  private uint uiDestinationIPAddress;   // Thirty two bit destination IP Address 

  //End IP Header fields   
  private byte byHeaderLength;             //Header length 
  private byte[] byIPData = new byte[4096]; //Data carried by the datagram
  public IPHeader(byte[] byBuffer, int nReceived)
    //Create MemoryStream out of the received bytes
    MemoryStream memoryStream = newMemoryStream(byBuffer, 0, nReceived);
    //Next we create a BinaryReader out of the MemoryStream
    BinaryReader binaryReader = newBinaryReader(memoryStream);

    //The first eight bits of the IP header contain the version and
    //header length so we read them
    byVersionAndHeaderLength = binaryReader.ReadByte();

    //The next eight bits contain the Differentiated services
    byDifferentiatedServices = binaryReader.ReadByte();
    //Next eight bits hold the total length of the datagram
    usTotalLength = 
             (ushort) IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

    //Next sixteen have the identification bytes
    usIdentification = 

    //Next sixteen bits contain the flags and fragmentation offset
    usFlagsAndOffset = 

    //Next eight bits have the TTL value
    byTTL = binaryReader.ReadByte();

    //Next eight represent the protocol encapsulated in the datagram
    byProtocol = binaryReader.ReadByte();

    //Next sixteen bits contain the checksum of the header
    sChecksum = IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

    //Next thirty two bits have the source IP address
    uiSourceIPAddress = (uint)(binaryReader.ReadInt32());

    //Next thirty two hold the destination IP address
    uiDestinationIPAddress = (uint)(binaryReader.ReadInt32());

    //Now we calculate the header length
    byHeaderLength = byVersionAndHeaderLength;

    //The last four bits of the version and header length field contain the
    //header length, we perform some simple binary arithmetic operations to
    //extract them
    byHeaderLength <<= 4;
    byHeaderLength >>= 4;

    //Multiply by four to get the exact header length
    byHeaderLength *= 4;

    //Copy the data carried by the datagram into another array so that
    //according to the protocol being carried in the IP datagram
               byHeaderLength, //start copying from the end of the header
               byIPData, 0, usTotalLength - byHeaderLength);
    catch (Exception ex)
        MessageBox.Show(ex.Message, "MJsniff", MessageBoxButtons.OK, 
//Please see the attached codes for the properties…

Firstly, the class contains the data members corresponding to the fields of the IP header. Kindly see RFC 791 for a detailed explanation of the IP header and its fields. The constructor of the class takes the bytes received and creates a MemoryStream on the received bytes and then creates a BinaryReader to read the data from the MemoryStream byte-by-byte. Also note that the data received from the network is in big-endian form so we use the IPAddress.NetworkToHostOrder to correct the byte ordering. This has to be done for all non-byte data members.

The TCP, UDP headers are also parsed in an identical fashion, the only difference is that they are read from the point where the IP header ends. As an example of parsing the application layer protocols, the attached project can detect DNS packets as well.



  • 9th February, 2008: Fixed the code to capture both incoming and outgoing packets. Thanks to Darren_vms for pointing this in the comments.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Hitesh Sharma
United States United States
No Biography provided

Comments and Discussions

Bugmax IP packet size is 65535, not 4096 Pin
David Jeske18-Oct-19 8:35
MemberDavid Jeske18-Oct-19 8:35 
QuestionHello. I'm korean. Pin
housdd25-Sep-19 20:31
Memberhousdd25-Sep-19 20:31 
QuestionCould not receive incoming message? Pin
cbfjay19-Sep-18 23:21
Membercbfjay19-Sep-18 23:21 
AnswerRe: Could not receive incoming message? Pin
cbfjay20-Sep-18 15:34
Membercbfjay20-Sep-18 15:34 
BugDoesn't work Pin
Robert Everett22-Oct-17 5:33
MemberRobert Everett22-Oct-17 5:33 
GeneralRe: Doesn't work Pin
Sims23-Oct-17 21:47
MemberSims23-Oct-17 21:47 
GeneralRe: Doesn't work Pin
Ganther830-Jul-19 23:21
MemberGanther830-Jul-19 23:21 
GeneralRe: Doesn't work Pin
David Jeske18-Oct-19 8:36
MemberDavid Jeske18-Oct-19 8:36 
QuestionData miner Pin
Member 117915295-Oct-17 20:12
MemberMember 117915295-Oct-17 20:12 
PraiseOutstanding work! Pin
Gil.Y5-Aug-17 14:46
MemberGil.Y5-Aug-17 14:46 
Thank you for this important article.Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup: Thumbs Up | :thumbsup:
Questionreport Pin
format C: /U23-Sep-15 21:07
Memberformat C: /U23-Sep-15 21:07 
QuestionDoesn't work with ssl traffic, Windows 10 Pin
Dmytro Yeremieiev14-Aug-15 9:47
MemberDmytro Yeremieiev14-Aug-15 9:47 
Questioncan Internet bandwidth be calculated this way? Pin
Amin Soltani31-May-15 21:32
MemberAmin Soltani31-May-15 21:32 
QuestionHow about ARP? Pin
ASM29935-Sep-14 3:59
professionalASM29935-Sep-14 3:59 
AnswerRe: How about ARP? Pin
MiguelAntonio30-Sep-14 14:49
MemberMiguelAntonio30-Sep-14 14:49 
GeneralMy vote of 4 Pin
Herre Kuijpers30-Jul-14 10:36
MemberHerre Kuijpers30-Jul-14 10:36 
Questionempty zip source file Pin
Member 1040682325-Jul-14 16:55
professionalMember 1040682325-Jul-14 16:55 
Questionthe attempted opeartion is not supported for the type of object refranced Pin
AminMhmdi18-Jun-14 16:08
professionalAminMhmdi18-Jun-14 16:08 
GeneralMy vote of 5 Pin
Member 1068660424-Mar-14 5:14
MemberMember 1068660424-Mar-14 5:14 
QuestionDouble packets Pin
PSU Mike7-Feb-14 1:11
MemberPSU Mike7-Feb-14 1:11 
GeneralMy vote of 1 Pin
applemeteor8-Dec-13 18:27
Memberapplemeteor8-Dec-13 18:27 
Questionhow to tell income or outgoing Pin
Huisheng Chen6-Jun-13 4:30
MemberHuisheng Chen6-Jun-13 4:30 
QuestionTrying to sniff on a local network Pin
Hammett199322-Apr-13 10:11
MemberHammett199322-Apr-13 10:11 
AnswerRe: Trying to sniff on a local network Pin
Michał Heliński22-Feb-18 0:19
MemberMichał Heliński22-Feb-18 0:19 
QuestionStart Sniff while Cable Disconnected? Pin
Ali Fakoor6-Feb-13 19:31
MemberAli Fakoor6-Feb-13 19:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.