Click here to Skip to main content
15,868,016 members
Articles / Programming Languages / C#
Article

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 867.5K   48.1K   334   154
A simple network sniffer which can parse IP, TCP, UDP, and DNS packets.
Sample Image - CSNetworkSniffer.jpg

Introduction

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

C#
// 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,
                       ProtocolType.IP);

// Bind the socket to the selected IP address
mainSocket.Bind(newIPEndPoint(IPAddress.Parse(cmbInterfaces.Text),0));

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

C#
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)
  {
    try
    {
    //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 = 
              (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

    //Next sixteen bits contain the flags and fragmentation offset
    usFlagsAndOffset = 
              (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

    //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
    Array.Copy(byBuffer, 
               byHeaderLength, //start copying from the end of the header
               byIPData, 0, usTotalLength - byHeaderLength);
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "MJsniff", MessageBoxButtons.OK, 
                        MessageBoxIcon.Error);
    }
 }
//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.

References

Updates

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

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: CDP package? Pin
draganmarkovic7-May-09 22:52
draganmarkovic7-May-09 22:52 
Questiongo work! Pin
datayang4-Jun-07 19:04
datayang4-Jun-07 19:04 
AnswerRe: go work! Pin
Hitesh Sharma4-Jun-07 20:01
Hitesh Sharma4-Jun-07 20:01 
GeneralExcellent work, I need some more information Pin
higauravbhai1-Jun-07 7:04
higauravbhai1-Jun-07 7:04 
GeneralRe: Excellent work, I need some more information Pin
Hitesh Sharma1-Jun-07 20:38
Hitesh Sharma1-Jun-07 20:38 
Questionhow do i get http Protocol? Pin
ee_ed7-May-07 9:52
ee_ed7-May-07 9:52 
GeneralRAW_SOCKS on VISTA Pin
JAGUARSOFT11-Apr-07 3:27
JAGUARSOFT11-Apr-07 3:27 
GeneralRe: RAW_SOCKS on VISTA Pin
Hitesh Sharma11-Apr-07 7:34
Hitesh Sharma11-Apr-07 7:34 
GeneralRe: RAW_SOCKS on VISTA Pin
funckynut22-Aug-07 1:56
funckynut22-Aug-07 1:56 
GeneralRe: RAW_SOCKS on VISTA Pin
Hitesh Sharma22-Aug-07 2:20
Hitesh Sharma22-Aug-07 2:20 
QuestionPacket Capturing for a LAN instead of a single local machine Pin
vighu24-Feb-07 3:32
vighu24-Feb-07 3:32 
GeneralRe: Packet Capturing for a LAN instead of a single local machine Pin
satish198723-Mar-08 3:25
satish198723-Mar-08 3:25 
GeneralRe: Packet Capturing for a LAN instead of a single local machine Pin
Hitesh Sharma23-Mar-08 6:22
Hitesh Sharma23-Mar-08 6:22 
GeneralInvalid argument was supplied Pin
dherv11-Jan-07 15:06
dherv11-Jan-07 15:06 
GeneralRe: Invalid argument was supplied Pin
Hitesh Sharma11-Jan-07 19:10
Hitesh Sharma11-Jan-07 19:10 
GeneralRe: Invalid argument was supplied Pin
JoeHegarty12-Jan-07 5:07
JoeHegarty12-Jan-07 5:07 
GeneralRe: Invalid argument was supplied Pin
JoeHegarty12-Jan-07 5:10
JoeHegarty12-Jan-07 5:10 
GeneralRe: Invalid argument was supplied Pin
Hitesh Sharma12-Jan-07 6:24
Hitesh Sharma12-Jan-07 6:24 
GeneralRe: Invalid argument was supplied Pin
learnVB20-Feb-07 10:10
learnVB20-Feb-07 10:10 
GeneralRe: Invalid argument :NO error Pin
crazycrackers25-Feb-07 21:58
crazycrackers25-Feb-07 21:58 
GeneralRe: Invalid argument :NO error [modified] Pin
dino20948-Mar-07 21:49
dino20948-Mar-07 21:49 
Questioni can't get another ip data Pin
Member 225534810-Jan-07 21:00
Member 225534810-Jan-07 21:00 
GeneralAwesome Pin
buraksarica9-Jan-07 1:35
buraksarica9-Jan-07 1:35 
GeneralRe: Awesome Pin
Hitesh Sharma9-Jan-07 2:03
Hitesh Sharma9-Jan-07 2:03 
GeneralRe: Awesome Pin
David Hanson3-Feb-07 11:10
David Hanson3-Feb-07 11:10 

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.