Friday, July 30, 2010

Network Sniffer

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 valueWhenever 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 are as shown below.

UDPHeader:

class UDPHeader
  {
      private ushort usSourcePort;            //Sixteen bits for the source port number       
      private ushort usDestinationPort;       //Sixteen bits for the destination port number
      private ushort usLength;                //Length of the UDP header
      private short sChecksum;                //Sixteen bits for the checksum
      //(checksum can be negative so taken as short)             
      //End UDP header fields

      private byte[] byUDPData = new byte[4096];  //Data carried by the UDP packet

      public UDPHeader(byte[] byBuffer, int nReceived)
      {
          MemoryStream memoryStream = new MemoryStream(byBuffer, 0, nReceived);
          BinaryReader binaryReader = new BinaryReader(memoryStream);

          //The first sixteen bits contain the source port
          usSourcePort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

          //The next sixteen bits contain the destination port
          usDestinationPort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

          //The next sixteen bits contain the length of the UDP packet
          usLength = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

          //The next sixteen bits contain the checksum
          sChecksum = IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

          //Copy the data carried by the UDP packet into the data buffer
          Array.Copy(byBuffer,
                     8,               //The UDP header is of 8 bytes so we start copying after it
                     byUDPData,
                     0,
                     nReceived - 8);
      }

      public string SourcePort
      {
          get
          {
              return usSourcePort.ToString();
          }
      }

      public string DestinationPort
      {
          get
          {
              return usDestinationPort.ToString();
          }
      }

      public string Length
      {
          get
          {
              return usLength.ToString();
          }
      }

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

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

TCPHeader

class TCPHeader
   {
       //TCP header fields
       private ushort usSourcePort;              //Sixteen bits for the source port number
       private ushort usDestinationPort;         //Sixteen bits for the destination port number
       private uint uiSequenceNumber = 555;          //Thirty two bits for the sequence number
       private uint uiAcknowledgementNumber = 555;   //Thirty two bits for the acknowledgement number
       private ushort usDataOffsetAndFlags = 555;      //Sixteen bits for flags and data offset
       private ushort usWindow = 555;                  //Sixteen bits for the window size
       private short sChecksum = 555;                 //Sixteen bits for the checksum
       //(checksum can be negative so taken as short)
       private ushort usUrgentPointer;           //Sixteen bits for the urgent pointer
       //End TCP header fields

       private byte byHeaderLength;            //Header length
       private ushort usMessageLength;           //Length of the data being carried
       private byte[] byTCPData = new byte[4096];//Data carried by the TCP packet

       public TCPHeader(byte[] byBuffer, int nReceived)
       {
           try
           {
               MemoryStream memoryStream = new MemoryStream(byBuffer, 0, nReceived);
               BinaryReader binaryReader = new BinaryReader(memoryStream);

               //The first sixteen bits contain the source port
               usSourcePort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //The next sixteen contain the destiination port
               usDestinationPort = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //Next thirty two have the sequence number
               uiSequenceNumber = (uint)IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());

               //Next thirty two have the acknowledgement number
               uiAcknowledgementNumber = (uint)IPAddress.NetworkToHostOrder(binaryReader.ReadInt32());

               //The next sixteen bits hold the flags and the data offset
               usDataOffsetAndFlags = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //The next sixteen contain the window size
               usWindow = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //In the next sixteen we have the checksum
               sChecksum = (short)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //The following sixteen contain the urgent pointer
               usUrgentPointer = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

               //The data offset indicates where the data begins, so using it we
               //calculate the header length
               byHeaderLength = (byte)(usDataOffsetAndFlags >> 12);
               byHeaderLength *= 4;

               //Message length = Total length of the TCP packet - Header length
               usMessageLength = (ushort)(nReceived - byHeaderLength);

               //Copy the TCP data into the data buffer
               Array.Copy(byBuffer, byHeaderLength, byTCPData, 0, nReceived - byHeaderLength);
           }
           catch (Exception ex)
           {
               MessageBox.Show(ex.Message, "MJsniff TCP" + (nReceived), MessageBoxButtons.OK, MessageBoxIcon.Error);
           }
       }

       public string SourcePort
       {
           get
           {
               return usSourcePort.ToString();
           }
       }

       public string DestinationPort
       {
           get
           {
               return usDestinationPort.ToString();
           }
       }

       public string SequenceNumber
       {
           get
           {
               return uiSequenceNumber.ToString();
           }
       }

       public string AcknowledgementNumber
       {
           get
           {
               //If the ACK flag is set then only we have a valid value in
               //the acknowlegement field, so check for it beore returning
               //anything
               if ((usDataOffsetAndFlags & 0x10) != 0)
               {
                   return uiAcknowledgementNumber.ToString();
               }
               else
                   return "";
           }
       }

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

       public string WindowSize
       {
           get
           {
               return usWindow.ToString();
           }
       }

       public string UrgentPointer
       {
           get
           {
               //If the URG flag is set then only we have a valid value in
               //the urgent pointer field, so check for it beore returning
               //anything
               if ((usDataOffsetAndFlags & 0x20) != 0)
               {
                   return usUrgentPointer.ToString();
               }
               else
                   return "";
           }
       }

       public string Flags
       {
           get
           {
               //The last six bits of the data offset and flags contain the
               //control bits

               //First we extract the flags
               int nFlags = usDataOffsetAndFlags & 0x3F;

               string strFlags = string.Format("0x{0:x2} (", nFlags);

               //Now we start looking whether individual bits are set or not
               if ((nFlags & 0x01) != 0)
               {
                   strFlags += "FIN, ";
               }
               if ((nFlags & 0x02) != 0)
               {
                   strFlags += "SYN, ";
               }
               if ((nFlags & 0x04) != 0)
               {
                   strFlags += "RST, ";
               }
               if ((nFlags & 0x08) != 0)
               {
                   strFlags += "PSH, ";
               }
               if ((nFlags & 0x10) != 0)
               {
                   strFlags += "ACK, ";
               }
               if ((nFlags & 0x20) != 0)
               {
                   strFlags += "URG";
               }
               strFlags += ")";

               if (strFlags.Contains("()"))
               {
                   strFlags = strFlags.Remove(strFlags.Length - 3);
               }
               else if (strFlags.Contains(", )"))
               {
                   strFlags = strFlags.Remove(strFlags.Length - 3, 2);
               }

               return strFlags;
           }
       }

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

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

       public ushort MessageLength
       {
           get
           {
               return usMessageLength;
           }
       }
   }

DNSHeader

class DNSHeader
   {
       //DNS header fields
       private ushort usIdentification;        //Sixteen bits for identification
       private ushort usFlags;                 //Sixteen bits for DNS flags
       private ushort usTotalQuestions;        //Sixteen bits indicating the number of entries
       //in the questions list
       private ushort usTotalAnswerRRs;        //Sixteen bits indicating the number of entries
       //entries in the answer resource record list
       private ushort usTotalAuthorityRRs;     //Sixteen bits indicating the number of entries
       //entries in the authority resource record list
       private ushort usTotalAdditionalRRs;    //Sixteen bits indicating the number of entries
       //entries in the additional resource record list
       //End DNS header fields

       public DNSHeader(byte[] byBuffer, int nReceived)
       {
           MemoryStream memoryStream = new MemoryStream(byBuffer, 0, nReceived);
           BinaryReader binaryReader = new BinaryReader(memoryStream);

           //First sixteen bits are for identification
           usIdentification = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Next sixteen contain the flags
           usFlags = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Read the total numbers of questions in the quesion list
           usTotalQuestions = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Read the total number of answers in the answer list
           usTotalAnswerRRs = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Read the total number of entries in the authority list
           usTotalAuthorityRRs = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());

           //Total number of entries in the additional resource record list
           usTotalAdditionalRRs = (ushort)IPAddress.NetworkToHostOrder(binaryReader.ReadInt16());
       }

       public string Identification
       {
           get
           {
               return string.Format("0x{0:x2}", usIdentification);
           }
       }

       public string Flags
       {
           get
           {
               return string.Format("0x{0:x2}", usFlags);
           }
       }

       public string TotalQuestions
       {
           get
           {
               return usTotalQuestions.ToString();
           }
       }

       public string TotalAnswerRRs
       {
           get
           {
               return usTotalAnswerRRs.ToString();
           }
       }

       public string TotalAuthorityRRs
       {
           get
           {
               return usTotalAuthorityRRs.ToString();
           }
       }

       public string TotalAdditionalRRs
       {
           get
           {
               return usTotalAdditionalRRs.ToString();
           }
       }
   }

So finally we are done.

Happy Sniffing.

please leave your comments and question and suggestions :)

Tuesday, July 27, 2010

Building first ASP.NET MVC Application

logo_300
Hello Guys,
Today We are gonna start with the Asp.Net Mvc development..
I Hope you people are also eager to learn it.....so let's begin with the work...
before starting with the development make sure that you have clear understanding of Asp.Net MVC basic and When to choose Asp.Net MVC ?

What You Should Know Before Developing an Asp.Net MVC Application


We make few assumptions about your technical background. We assume that you know the C# .NET programming language — all the code samples will be in c# also assume that you know basic HTML. ASP.NET MVC uses many advanced features of the C# .NET language.

What Software Do You Need?

You can download all the software that you need to build ASP.NET MVC applications from here. You need to install three software components:
1. Microsoft .NET Framework 3.5 Service Pack 1 The Microsoft .NET framework includes the Microsoft ASP.NET framework.
2. Microsoft ASP.NET MVC 1.0—The actual ASP.NET MVC framework that runs on top of the ASP.NET framework.
3. Microsoft Visual Web Developer 2008 Service Pack 1 or Microsoft Visual Studio

Understanding the Sample ASP. NET MVC Application


A good way to get a firmer grasp on the three logical parts of an MVC application is to take a look at the sample application that is created automatically when you create a new ASP.NET MVC project with Visual Studio.
Follow these steps :
1. Launch Visual Studio.
2. Select the menu option File, New Project.
3. In the New Project dialog, select your programming language as C#  and select the ASP.NET MVC Web Application template. Give your project the name MyFirstMvcApp and click the OK button.
Note : I am using VS 2010 so its having latest release of MVC that is MVC 2 that is why it is showing "ASP.NET MVC 2 Web Application" otherwise You will have simple "ASP.NET MVC Web Application" in VS 2008. Make sure that you select the .NET Framework 3.5 as the target framework.
4.Immediately after you click the OK button to create a new ASP.NET MVC project, you see the Create Unit Test Project dialog shown in the below snap.Leave the default option selected—Yes, Create a Unit Test Project—and click the OK button.
5. Visual Studio creates the default files for a new ASP.NET MVC project. After all the files are created, the Solution Explorer window should contain the files shown in the below image :
The Solution Explorer window in above Figure contains two separate projects: the ASP.NET MVC project and the Test project. The Test project contains all the unit tests for your application.

ASP.NET MVC Folder Conventions


The ASP.NET MVC framework emphasizes convention over configuration. There are standard locations for each type of file in an ASP.NET MVC project. The ASP.NET MVC application project contains the following folders:
  • App_Data—Contains database files. For example, the App_Data folder might contain a local instance of a SQL Server Express database.
  • Content—Contains static content such as images and Cascading Style Sheet files.
  • Controllers—Contains ASP.NET MVC controller classes.
  • Models—Contains ASP.NET MVC model classes.
  • Scripts—Contains JavaScript files including the ASP.NET AJAX Library and jQuery.
  • Views—Contains ASP.NET MVC views.
When building an ASP.NET MVC application, you should place controllers only in the Controllers folder, JavaScript scripts only in the Scripts folder, ASP.NET MVC views only in the Views folder, and so on. By following these conventions, your application is more easily maintained, and it can be more easily understood by others.

Running the Sample ASP.NET MVC Application


When you create a new ASP.NET MVC application, you get a simple sample application. You can run this sample application by selecting the menu option Debug, Start Debugging (or press the F5 key).
The first time that you run a new ASP.NET MVC application in Visual Studio, you receive a dialog asking if you want to enable debugging. Simply click the OK button.
When you run the application, your browser opens with the page in Figure below :

This sample application is implemented with one ASP.NET MVC controller and two ASP.NET MVC views. The sample application does not contain any business or data access logic, so it does not contain any ASP.NET MVC model classes.
The controller is located in the Controllers folder:
\Controllers\HomeController.cs
If you open the HomeController in the Code Editor window, you will see the code as below :
Controllers\HomeController.cs


There are two methods named Index( ) and About() . Methods exposed by a controller are called actions. Both the Index() and About() actions return a view.
When you first run the sample application, the Index() action is invoked and this action returns the Index view. If you click the About tab, the About( ) action is invoked and this action returns the About view.
The two views can be found in the Views folder at the following location:
\Views\Home\About.aspx
\Views\Home\Index.aspx
The content of the Index view is contained as below :

Notice that a view consists mostly of standard HTML content. For example, the view contains standard <h2> and <p> tags. A view generates a page that is sent to the browser.
That's it...!!!
You learned how the ASP.NET MVC framework implements the Model View Controller pattern and how ASP.NET MVC enables you to perform pattern-based software development.
So ? how was the first ride to ASP.NET MVC Sample Application ?? :-)  I Hope it would be great... :-)
Hope this helps...

Youtube Video search and play control

logo_300
Today we gonna tell about making a project that could extract the video from YouTube using a keyword entered by the user and then playing it.
We’ll make a control and you would be able to use it any where you want.
Before going forward let me tell you what u’ll need for it.
You’ll need a developer key issued by Google to make use of any of Google API. here we’ll be using YouTube API.
here are some links.
http://code.google.com/apis/youtube/dashboard/ (for getting DEV key)
http://code.google.com/apis/youtube/code.html#client_libraries( Download API).
So let me tell you how it gonna look like
image
Designing is pretty easy
  • just take one panel
  • set dock property to top
  • right click over it and press bring to front
  • drag and drop a textbox and a button inside it and align them
  • take a flowlayout panel
  • set dock property to fill
  • right click over it and choose bring to front.
So now you are completed with design
so i guess we should start coding don’t you?. really excited to listen songs in your apps. ;)
so here we go
Class variables are as given
string id; static public Point loc; public bool Search; public string currentlink = ""; string item; bool feed; Feed<Video> yt_vid; YouTubeRequestSettings Ysettings = new YouTubeRequestSettings("Your app name", "Your app name", "Your Dev key", "Username","Password"); YouTubeRequest Yrequest; public static YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri); List<Video> _vidlist = new List<Video>(); YouTubeService Yservice = new YouTubeService(Your app name", "Your app name", "Your Dev key"); static public List<AtomCategory> atcat = new List<AtomCategory>(); static public List<string> cat_vid = new List<string>();
So i guess you need some explanations that what are these strange things don’t you?
Well. String id is for our Video ID, its a simple id that you see in any Video URL of Youtube.
Current link will give us the the link of selected Video.
Some important variables are
  • YouTubeRequestSettings : It’ll provide settings for your application. It takes mentioned parameters and all of them are string. It’ll used for making our YouTubeRequest Variable
  • Youtube querry will be used or searching video
  • List of video has been taken as the number of extracted video can be any thing from 0 to 25 or even more.so i have taken list instead of array
  • Another one is YouTubeService
  • List<AtomCategory> has been choiosen for choosing catagory of video
Click event of button will be as shown
private void button1_Click(object sender, EventArgs e) { Search = true; Yrequest = new YouTubeRequest(Ysettings); this.item = txtSearch.Text; query.Query = item.Replace(' ', '+'); yt_vid = Yrequest.Get<Video>(query); for (int i = 1; i < 3; i++) {
this.Height *= i; flowLayoutPanel1.Height *= i; } printvids(); Search = false; }
So you can see we have used Youtube settings for making Youtube request.
we took the search term and assign that to the youtubequery
in the next line we just increased the size of Flowlayout panel.
printvids function is as given below
void printvids() {
foreach (Video entry in yt_vid.Entries) { foreach (MediaContent Mcon in entry.Contents) { try {
int x = Mcon.Url.IndexOf('?'); id = Mcon.Url.Remove(x); id = id.Substring(25);
Label lblviewcount = new Label(); lblviewcount.ForeColor = Color.White; lblviewcount.Text = entry.ViewCount + " VIEWS"; lblviewcount.Width = flowLayoutPanel1.Width;
PictureBox img = new PictureBox(); img.SizeMode = PictureBoxSizeMode.StretchImage; //Bitmap bmp = new Bitmap("http://img.youtube.com/vi/_XUe6Obeyk0/0.jpg"); img.ImageLocation = "http://img.youtube.com/vi/" + id + "/0.jpg"; img.Width = 170; img.Height = 170; img.Left = flowLayoutPanel1.Left;
LinkLabel lblName = new LinkLabel(); lblName.AccessibleName = id; lblName.ForeColor = Color.White; lblName.Text = entry.Title.ToString(); lblName.Width = flowLayoutPanel1.Width; lblName.Click += new EventHandler(lnk_click); flowLayoutPanel1.Controls.Add(lblviewcount); flowLayoutPanel1.Controls.Add(img); flowLayoutPanel1.Controls.Add(lblName);
//if (flowLayoutPanel1.InvokeRequired) //{ //    connect add = new connect(addcontrol); //    object[] param = new object[3]; //    param[0]= lblName; //    param[1]=lblviewcount; //    param[2]=img; //    flowLayoutPanel1.BeginInvoke(add); //} } catch (Exception ex) { }
}
} }
In the click event of button we had extracted the videos and added them into Feed<Video>
In this method we extract video from the feed and the video infos from the video to print to the form, so we extracted the infos into MediaContent.
using following lines we got the id of Youtube video
int x = Mcon.Url.IndexOf('?'); id = Mcon.Url.Remove(x); id = id.Substring(25);
Using MediaContent we extracted infos like URL and Thumbnail of the videos. and as we got them added into linklabel, label and picture box and added them into Flowlayout control to display them on our Control.
By now we have created Search control
Now will do something that will be able to play video extracted from Youtube.
It’ll be quite easy as we are going to just create an html file and then embedding code of video in that html file
Now we will do it by clicking on linklabel.
So we need a form that will contain a web browser to run our .htm file .
The click event of the linklabel hase been defind in the above method
The event definition will be as given
private void lnk_click(object sernder, EventArgs e) { LinkLabel lnk = (LinkLabel)sernder; id = lnk.AccessibleName; Save("video.htm");                                                                                                 Player ob = new Player(); ob.Show(); }
PLayer is another form  that contains our web browser.
Here we created a link label and assinged the ID of selected video as shown above. in the previous method we had taken id of video in the accessible name of linklabel. so we got the selected video id.
Now we need to write embedding code to the html file. the save method does the same.
But be sure to add an html file exclusively to your project and pass the name of the html file to save method.
Save method is as shown below
public void Save(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite); StreamWriter sw = new StreamWriter(fs); try { string  Embedcode =@”<body style=" + "background:#000000" + ">" + "<div id=\"video" + id + "\"><object width=\”425\” height=\"355\"><param name=\"movie\" value=\"http://www.youtube.com/v/"+ id + "&rel=1\"></param><param name=\"wmode\" value=\"transparent\”></param><embed src=”\"http://www.youtube.com/v/" + id + "&rel=1\"type=\"application/x-shockwave-flash\" wmode=\"transparent\" width=\"425\" height=\"355\">></embed></object></div></body>";”
sw.WriteLine(Embedcode); }
finally { sw.Close(); fs.Close(); } }
Embedcode has been defined and written in the html file.
rest of the line of click event of LinkLabel just show the Player form.
The load event of the Player form is as given below
private void Player_Load(object sender, EventArgs e) { this.Left = UserControl1.loc.X; this.Top = UserControl1.loc.Y; string path = Path.GetFullPath("video.htm"); webBrowser1.Navigate(path); }
Now would you like to believe that you have just coded your very own Youtube Control. :)
Here’s the working snap
image
Hope you’ll find this post useful. Keep on posting suggestions and questions.
THX
You can get our working project on youtube from http://syd.codeplex.com.