Netwrok Sniffer

Published on by Inno Design

I was looking for this project from a long time before thanks to MJSniffer project from where i got definitions for Packets. Let’s make it today.

A sample program can be downloaded from here.

Network sniffer is a kind of application that sniffs or captures the information in incoming and out going packets from your Machine. There are so many such applications. So i decided to make on my own. so i guess you to will think the same.

Here i have added definitions for following protocols

  • TCP
  • UDP
  • IP
  • DNS
  • others are named as unknown

The designing is very simple. Just put a list view and add four column namely

  • serial number
  • Version
  • Source Address
  • Destination Address A button and a text box, take some labels to show some message as shown in picture (along with the text box).
The look will ne as

image

the process is coding is very simple.

We get the input as an IP address of the machines where sniffer has to be performed. We will create a socket and will bind that to that address and it’ll go in infinite loop capturing all packets.

the top level variables mean those which are out of any methods are as follows

        List<byte[]> bufs = new List<byte[]>(); 
        List<IpHeader> A_ipheader = new List<IpHeader>(); 
        Socket Scksnif; 
        delegate void insertinto(object obj); 
        bool is_Snifing = false; 
        private byte[] byteData = new byte[4096];

Bool Is_Sniffing tells whether sniffer is working or not.

scksnif is our socket.

Delegate will be used for accessing the controls as we will be using threads.

The click event of button will be as this

private void toolStripButton1_Click(object sender, EventArgs e) 
      { 
          if (!is_Snifing && !string.IsNullOrEmpty(txtMachinesIP1.Text)) 
          { 
              try 
              { 
                  is_Snifing=true;                   
                  Scksnif = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP); 
                  Scksnif.Bind(new IPEndPoint(Dns.GetHostByAddress(IPAddress.Parse(txtMachinesIP1.Text)).AddressList[0],0)); 
                  Scksnif.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true); 
                  byte[] byTrue = new byte[4] { 1, 0, 0, 0 }; 
                  byte[] byOut = new byte[4] { 1, 0, 0, 0 }; 
                  Scksnif.IOControl(IOControlCode.ReceiveAll, byTrue, byOut); 
                  this.toolStripButton2.Image = global::MyNWproject.Properties.Resources._48px_Process_stop_svg; 
                  Scksnif.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(Callback), null); 
              } 
              catch (Exception x) { MessageBox.Show(x.Message, "Error Reported", MessageBoxButtons.OK, MessageBoxIcon.Error); } 
          } 
          else 
          { 
              is_Snifing = false; 
              this.toolStripButton2.Image = global::MyNWproject.Properties.Resources.btnStart; 
              Scksnif.Close(); 
          } 
      }

 

In above event we had checked for two condition whether sniffer is working or not and whether IP address textbox is empty.

when these conditions are true we’ll move inside a try block.

Initiate a socket instance. The constructor of socket class is overloaded.

It’ll take three arguments

Addressfamily is set to InterNetwork for supporting all IPv 4 type address what we are using.

SocketType has been set to Raw

ProtocolType has been set to IP we want our socket to support IP.

After this we binded the socket to the IPEndPoint (created by IP entered by user).

IPEndPoint is set to ‘0’ port number to take any available port.

Next to this socketOption is created.

SocketLevel set the option that to which protocol socket is to Apply. we have created this for IP

Two byte arrays are created for Input and out put.

Socket.Iocontrol set the operating mode of  socket using Codes.

next to this just changed the Image of tool strip button and next to that started receiving packets.

But how can it be so simple, Just an event must not be enough for capturing packets isn’t it. Now see carefully beginerecieve method takes some parameters among them one is Asynccallback, that takes a parameter which is a method. Bytedata will be out packet received.

Callback method is like this.

void Callback(IAsyncResult result) 
        { 
            try 
            { 
                int Nums = Scksnif.EndReceive(result); 
                ParseData(byteData, Nums); 
                if (is_Snifing) 
                { 
                    byteData = new byte[4096]; 
                    Scksnif.BeginReceive(byteData, 0, byteData.Length, SocketFlags.None, new AsyncCallback(Callback), null); 
                } 
            } 
            catch (Exception x) { } 
        }

 

Callback method takes a parameter named result of Type IAsyncResult which is an Interface.

Now Scksnif.EndReceive(result); ends pending async reads.the int returned by this will return the number of bytes received.

Parsedata method will create an instance of IPheader and will call a method that will perform filling data into the list view.

Rest of code is for re-beginning receiving  of data and hence calling callback recursively.

The Parse data method is As given below

void ParseData(byte[] buffer, int nums) 
        { 
            IpHeader ipheader = new IpHeader(buffer, nums); 
            insertsniffdata_IP(ipheader); 
        }

 

IPheader constructor takes two arguments the byte received and the number of bye received.

IPHeader Class is as.

class IpHeader 
    { 
         //IP Header fields 
        private byte      byVersionAndHeaderLength;   //Eight bits for version and header length 
        private byte      byDifferentiatedServices;    //Eight bits for differentiated services (TOS) 
        private ushort    usTotalLength;              //Sixteen bits for total length of the datagram (header + message) 
        private ushort    usIdentification;           //Sixteen bits for identification 
        private ushort    usFlagsAndOffset;           //Eight bits for flags and fragmentation 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 containing the checksum of the header 
                                                      //(checksum can be negative so taken as short) 
        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 = new MemoryStream(byBuffer, 0, nReceived); 
                //Next we create a BinaryReader out of the MemoryStream 
                BinaryReader binaryReader = new BinaryReader(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 represnts 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 airthmatic 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 data gram 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, "MJsniffer", MessageBoxButtons.OK, 
                MessageBoxIcon.Error); 
        } 
        }

        public string Version 
        { 
            get 
            { 
                //Calculate the IP version

                //The four bits of the IP header contain the IP version 
                if ((byVersionAndHeaderLength >> 4) == 4) 
                { 
                    return "IP v4"; 
                } 
                else if ((byVersionAndHeaderLength >> 4) == 6) 
                { 
                    return "IP v6"; 
                } 
                else 
                { 
                    return "Unknown"; 
                } 
            } 
        }

        public string HeaderLength 
        { 
            get 
            { 
                return byHeaderLength.ToString();                
            } 
        }

        public ushort MessageLength 
        { 
            get 
            { 
                //MessageLength = Total length of the datagram – Header length 
                return (ushort)(usTotalLength – byHeaderLength); 
            } 
        }

        public string DifferentiatedServices 
        { 
            get 
            { 
                //Returns the differentiated services in hexadecimal format 
                return string.Format ("0x{0:x2} ({1})", byDifferentiatedServices, 
                    byDifferentiatedServices); 
            } 
        }

        public string Flags 
        { 
            get 
            { 
                //The first three bits of the flags and fragmentation field 
                //represent the flags (which indicate whether the data is 
                //fragmented or not) 
                int nFlags = usFlagsAndOffset >> 13; 
                if (nFlags == 2) 
                { 
                    return "Don’t fragment"; 
                } 
                else if (nFlags == 1) 
                { 
                    return "More fragments to come"; 
                } 
                else 
                { 
                    return nFlags.ToString(); 
                } 
            } 
        }

        public string FragmentationOffset 
        { 
            get 
            { 
                //The last thirteen bits of the flags and fragmentation field 
                //contain the fragmentation offset 
                int nOffset = usFlagsAndOffset << 3; 
                nOffset >>= 3;

                return nOffset.ToString(); 
            } 
        }

        public string TTL 
        { 
            get 
            { 
                return byTTL.ToString(); 
            } 
        }

        public Protocol ProtocolType 
        { 
            get 
            { 
                //The protocol field represents the protocol in the data portion 
                //of the datagram 
                if (byProtocol == 6)        //A value of six represents the TCP protocol 
                { 
                    return Protocol.TCP; 
                } 
                else if (byProtocol == 17)  //Seventeen for UDP 
                { 
                    return Protocol.UDP; 
                } 
                else 
                { 
                    return Protocol.Unknown; 
                } 
            } 
        }

        public string Checksum 
        { 
            get 
            { 
                //Returns the checksum in hexadecimal format 
                return string.Format ("0x{0:x2}", sChecksum); 
            } 
        }

        public IPAddress SourceAddress 
        { 
            get 
            { 
                return new IPAddress(uiSourceIPAddress); 
            } 
        }

        public IPAddress DestinationAddress 
        { 
            get 
            { 
                return new IPAddress(uiDestinationIPAddress); 
            } 
        }

        public string TotalLength 
        { 
            get 
            { 
                return usTotalLength.ToString(); 
            } 
        }

        public string Identification 
        { 
            get 
            { 
                return usIdentification.ToString(); 
            } 
        }

        public byte[] Data 
        { 
            get 
            { 
                return byIPData; 
            } 
        }

    }

This class is commented so i think no need to describe it.

Method insertsniffdata_IP is as given below

void insertsniffdata_IP(IpHeader ipheader) 
      { 
          if (listView1.InvokeRequired) 
          { 
              insertinto inst = new insertinto(insert); 
              listView1.BeginInvoke(inst, ipheader);                
          } 
      }

This method checks whether listview need the meain thread to be accessed and if then access it using Main thread only. insertinto was our delegate and insert is the method that feels the data into the listView.

Insert method is as given

void insert(object obj) 
       { 
           IpHeader ipheader = (IpHeader)obj; 
           listView1.Items.Add(new ListViewItem(new string[] { global.ToString(), ipheader.Version, ipheader.SourceAddress.ToString(), ipheader.DestinationAddress.ToString() })); 
           A_ipheader.Add(ipheader); 
           global++; 
       }

The various values inserted you can check from the the definition of IPheader class.

A_ipheader is a list of Ipheader we are adding current Ipheader to that. this way the index of values in row of listview and that of A_ipheader will be same.

Now Another feature of our sniffer. Its not actually a feature but it’ll become so messy if i would have put all the data over front listview so i decided to put detail information on another window.

Another window will contain a listview with two column

  • Property name
  • property value
  • Whenever user will click on any of row of listview of main window this window will appear.

For this create a Double click event of ListView.
The event will be as given below

private void listView1_DoubleClick(object sender, EventArgs e) 
       { 
           ListView l= (ListView) sender; 
           DetailSnifer obj = new DetailSnifer(); 
           obj.ipheader1=(IpHeader) A_ipheader[l.SelectedItems[0].Index]; 
           obj.ShowDialog(); 
       }

Here we have created an instance of Detailsniffer class which will create our window that’ll show the detail values extracted by the sniffer.

Ipheader1 is an instance of IpHeader class created in DeatilSniffer class. we set that equal to current instance of Ipheader using selected row index (as index of listview and index of A_IpHeader corresponds to same instance of Ipheader, as told above).

The load event of DetailSniffer is as shown Below

private void DetailSnifer_Load(object sender, EventArgs e) 
        { 
            IpHeader ipheader=(IpHeader) ipheader1; 
            insert_ip(ipheader); 
            switch (ipheader.ProtocolType) 
            { 
                case Protocol.TCP: 
                    TCPHeader tcp= new TCPHeader(ipheader.Data,ipheader.Data.Length); 
                    if (tcp.DestinationPort == "53" || tcp.SourcePort == "53") 
                    { 
                        insert_DNS(tcp.Data, (int)tcp.MessageLength); 
                    } 
                    insert_Tcp(tcp); 
                    break; 
                case Protocol.UDP: 
                    UDPHeader udpHeader = new UDPHeader(ipheader.Data, ipheader.Data.Length); 
                    if (udpHeader.DestinationPort == "53" || udpHeader.SourcePort == "53") 
                    {

                        insert_DNS(udpHeader.Data,Convert.ToInt32(udpHeader.Length) – 8);                       
                    } 
                    insert_UDP(udpHeader); 
                    break; 
                case Protocol.Unknown: 
                    break; 
                default: 
                    break; 
            } 
        }

 

Here we have checked for which protocol is the ipheader corresponds to and extracted values according to that.

Insert methods used are as given below

Insert_Ip

void insert_ip(IpHeader ipheader) 
       { 
           listView1.Items.Add(new ListViewItem(new string[] { "Source", ipheader.SourceAddress.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Destintion", ipheader.DestinationAddress.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Version", ipheader.Version.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Differentiated Srvice", ipheader.DifferentiatedServices.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Total Length", ipheader.TotalLength.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Identification", ipheader.Identification.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Flags", ipheader.Flags.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Fragmentation", ipheader.FragmentationOffset.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "TTL", ipheader.TTL.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Data", Encoding.UTF8.GetString(ipheader.Data)})); 
           listView1.Items.Add(new ListViewItem(new string[] { "Protocol", ipheader.ProtocolType.ToString() })); 
           listView1.Items.Add(new ListViewItem(new string[] { "Checksum", ipheader.Checksum.ToString() })); 
           textBox1.Text = Encoding.UTF8.GetString(ipheader.Data).GetHashCode().ToString();

       }

insert_Tcp

void insert_Tcp(TCPHeader tcp) 
        { 
            listView1.Items.Add(new ListViewItem(new string[] { "Source Port", tcp.SourcePort.ToString() })); 
            listView1.Items.Add(new ListViewItem(new string[] { "Destination Port", tcp.DestinationPort.ToString() })); 
            listView1.Items.Add(new ListViewItem(new string[] { "Sequence Number", tcp.SequenceNumber.ToString() })); 
            listView1.Items.Add(new ListViewItem(new string[] { "Acknowledge Number", tcp.AcknowledgementNumber.ToString() })); 
            listView1.Items.Add(new ListViewItem(new string[] { "Header Length", tcp.HeaderLength.ToString() })); 
            listView1.Items.Add(new ListViewItem(new string[] { "Flags", tcp.Flags.ToString() })); 
            listView1.Items.Add(new ListViewItem(new string[] { "Window Size", tcp.WindowSize.ToString() })); 
            listView1.Items.Add(new ListViewItem(new string[] { "Check Sum", tcp.Checksum.ToString() })); 
        }

 

insert_DNS

void insert_DNS(byte[] buffer, int nums) 
        { 
            DNSHeader dnsHeader = new DNSHeader(buffer, nums);                       
            listView1.Items.Add(new ListViewItem(new string[] {"Identification", dnsHeader.Identification})); 
            listView1.Items.Add(new ListViewItem(new string[] {"Flags", dnsHeader.Flags})); 
            listView1.Items.Add(new ListViewItem(new string[] {"Questions", dnsHeader.TotalQuestions})); 
            listView1.Items.Add(new ListViewItem(new string[] {"Answer RRs", dnsHeader.TotalAnswerRRs})); 
            listView1.Items.Add(new ListViewItem(new string[] {"Authority RRs", dnsHeader.TotalAuthorityRRs})); 
            listView1.Items.Add(new ListViewItem(new string[] { "Additional RRs", dnsHeader.TotalAdditionalRRs })); 
        }

insert_UDP

void insert_UDP(UDPHeader udpHeader) 
        { 
            listView1.Items.Add(new ListViewItem(new string[] {"Source Port", udpHeader.SourcePort})); 
            listView1.Items.Add(new ListViewItem(new string[] {"Destination Port", udpHeader.DestinationPort})); 
            listView1.Items.Add(new ListViewItem(new string[] {"Length", udpHeader.Length})); 
            listView1.Items.Add(new ListViewItem(new string[] {"Checksum", udpHeader.Checksum})); 
            listView1.Items.Add(new ListViewItem(new string[] { "Data", Encoding.ASCII.GetString(udpHeader.Data) })); 
        }

Definitions of various Protocol header classes can be downloaded from the sample application

So finally we are done.

Happy Sniffing.

please leave your comments and question and suggestions :)

Published on Networking

Comment on this post