Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
6 Months Free & No Setup Fees ASP.NET Hosting!
Search :       Advanced Search »
Home » Visual C# » Packet Sniffer in C#

Packet Sniffer in C#

The attached source code is a packet sniffer. Most of featured came from ethereal.

Page Views : 92873
Downloads : 5321
Rating :
 Rate it
Level : Intermediate
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
Pacanal.zip
 
 
Team Foundation Server Hosting
Become a Sponsor
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

The attached source code is a packet sniffer. Most of featured came from ethereal. I used WinPCap libraries to do it. But the most important difference is my code only uses npf.sys of WinPCap. I ported all the function int PacketNtx.dll to C#. As I said, the features of it like ethereal which are,

  • You can stop a capture session by,
  • when a specified time duration has passed
  • when specified bytes of data captured
  • when a number of specified packets captured
  • when stop button pressed
  • You can limit the size of the packets to a specified length.You can enable/disable MAC name resolution
  • You can enable the live scrolling the captured packets
  • You can change the hardware filter
  • You can change capture mode
  • You can change Adapter Buffer size, Read Buffer size , Timeout value etc.
  • You can highlight the protocol data by either clicking the protocol node or the protocol data itself.
  • You can see the index of a protocol data and the length of it
  • You can save the captured packets int he format that ethereal understands
  • You can load a packet file captured by ethereal
  • You can partially save the captured packet by selecting them
  • You can copy the protocol data to clipboard in the format string and in the hex layout by selecting the start and stop points
  • You can sort the captured packets as desired

The code is pure managed. and it supports about 20 protocols which are,

  • ETHERNET
  • LLC
  • STP
  • NETBIOS
  • CDP
  • INTERNET
  • TCP
  • UDP
  • HTTP
  • ICMP
  • ARP
  • LOOPBACK
  • NBDS
  • NBNS
  • NBSS
  • SMB MAILSLOT
  • SMB - Not finished yet
  • DCERPC
  • DLSW - Almost finished
  • DNS - Not finished yet
  • IPX
  • TFTP
  • EIGRP

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Fyrat Kocak
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
 Comments
Getting error by navaneeth On February 5, 2007
Hi I downloaded the application. I am getting several registry values error when starting the program. It is giving index was out of bounds error when i press start button.. Pls help Navaneeth
Reply | Email | Modify 
Missing reference by Zdenek On June 26, 2007
Hi I downloaded the code and did not find the MyClasses.dll :(
Reply | Email | Modify 
Re: Missing reference by jacob On July 21, 2007
Hi I also downloaded the code and I also can did find the MyClasses.dll :(
Reply | Email | Modify 
Re: Re: Missing reference by sri On January 31, 2008

hi, i also download it.but can't find myclasses....plz help me???

Reply | Email | Modify 
Wireless by Adriana On September 23, 2007
This software capture IP packets from a wireless, too?
Reply | Email | Modify 
Help Me by Ramin On September 26, 2007
HI, i'm download this project, but do not runing.Error: do not find MyClasses.dll. plz help me Best regards
Reply | Email | Modify 
NetworkMiner works better by Erik On November 25, 2007
If you have problems with this application then I suggest you try "NetworkMiner packet analyzer" instead. It is also written in C#, can sniff and alalyze network traffic and is available as open source (from sourceforge). http://sourceforge.net/projects/networkminer/
Reply | Email | Modify 
Erorr by Hai On December 25, 2007
It's doen't work when i open it in C# 2005 :(
Reply | Email | Modify 
Re: Erorr by Zero On March 7, 2008
You have to convert the project to a newer version before you can use it.
Reply | Email | Modify 
Missing MYclasses as references by sri On January 31, 2008
hello..how to get the myclasses??/plz help me??
Reply | Email | Modify 
Re: Missing MYclasses as references by Zero On March 7, 2008
Download it from my Rapidshare-Folder: http://rapidshare.com/files/97792934/MyClasses.dll
Reply | Email | Modify 
MyClasses.dll by Zero On March 7, 2008
This DLL is already included - just as another project which isn't build. If you don't know, what to do or anything else, download this file from my folder: http://rapidshare.com/files/97792934/MyClasses.dll Copy it to your Debug folder. It should work zero5
Reply | Email | Modify 
i have a problem..... by asdasd On December 7, 2008
the application wont find adapters.... PacketOpenAdapter - fails
Reply | Email | Modify 
HTTPONLY cookie by Pallavi On September 30, 2009
hey anyidea how to access httpcookie on the client side? its really urgent please reply
Reply | Email | Modify 
netdump.c by Ras On October 28, 2009
hi...

i have a netdump.c coding to capture packets but i've been trying to modify the code to display only TCP/IP packets. Do you happen to know the coding to perform that.

Reply | Email | Modify 
abt this sniffer by sravan On November 3, 2009
is it possible for me to get the complete project setup file and doc i need to study the entire project
Reply | Email | Modify 
urgent help required by hunza On November 16, 2009
Hi
I m getting the error that MyClasses.dll is not found.I hav also checked the link u hav provided but i havn't found any thing there, kindly help me in this regard..
Reply | Email | Modify 
help me complete this code where commented by Ras On November 19, 2009

#define NULL 0

#define TCPDUMP_MAGIC 0xa1b2c3d4        /* Tcpdump Magic Number (Preamble)  */

#define PCAP_VERSION_MAJOR    2     /* Tcpdump Version Major (Preamble) */

#define PCAP_VERSION_MINOR    4     /* Tcpdump Version Minor (Preamble) */

 

#define DLT_NULL  0                           /* Data Link Type Null  */

#define DLT_EN10MB 1    /* Data Link Type for Ethernet II 100 MB and above */

#define DLT_EN3MB 2     /* Data Link Type for 3 Mb Experimental Ethernet */

 

// Ethernet Header

#define ETHER_ADDR_LEN 6

#include <stdio.h>

#include <iostream>

#include <fstream>

using namespace std;

 

FILE *input;

 

typedef struct packet_header

{

      unsigned int magic;                       /* Tcpdump Magic Number */

      unsigned short version_major;       /* Tcpdump Version Major */

      unsigned short version_minor;     /* Tcpdump Version Minor */

      unsigned int thiszone;                  /* GMT to Local Correction */

      unsigned int sigfigs;                   /* Accuracy of timestamps */

      unsigned int snaplen;         /* Max Length of Portion of Saved Packet */

      unsigned int linktype;                  /* Data Link Type */

} hdr;

 

typedef struct packet_timestamp

{

      unsigned int tv_sec;                   /* Timestamp in Seconds */

      unsigned int tv_usec;                   /* Timestamp in Micro Seconds */

      /* Total Length of Packet Portion (Ethernet Length until the End of Each Packet) */

      unsigned int caplen;

      unsigned int len;                 /* Length of the Packet (Off Wire) */

} tt;

 

typedef struct ether_header

{     unsigned char edst[ETHER_ADDR_LEN]; /* Ethernet Destination Address */

      unsigned char esrc[ETHER_ADDR_LEN];  /* Ethernet Source Address */

      unsigned short etype;                  /* Ethernet Protocol Type */

} eth;

 

int main(int argc, char *argv[])

{

     

      unsigned int remain_len = 0;

      unsigned char temp=0, hlen, version, tlen;

      int i, count=0;

 

      struct packet_header hdr;     /* Initialize Packet Header Structure */

      struct packet_timestamp tt;   /* Initialize Timestamp Structure */

      struct ether_header eth;      /* Initialize Ethernet Structure */

    unsigned char buff, array[1500];

 

      input = fopen("abc", "rb");         /* Open Input File */

      if(fopen == NULL)

            cout << "Cannot open saved windump file" << endl;

      else

      {

      /* Read & Display Packet Header Information */

            fread((char *) &hdr, sizeof(hdr), 1, input);               

            cout << "\n********** ********** PACKET HEADER ********** ***********" << endl;

            cout << "Preamble " << endl;

            cout << "Packet Header Length : " << sizeof(hdr) << endl;

            cout << " Magic Number : " << hdr.magic << endl;

            cout << "Version Major : " << hdr.version_major << endl;

            cout << "Version Minor : " << hdr.version_minor << endl;

            cout << "GMT to Local Correction : " << hdr.thiszone << endl;

            cout << "Jacked Packet with Length of : " << hdr.snaplen << endl;

            cout << "Accuracy to Timestamp   :  " << hdr.sigfigs  << endl;

            cout << "Data Link Type (Ethernet Type II = 1)  : " << hdr.linktype << endl;

 

            /* Use While Loop to Set the Packet Boundary */

            while(fread((char *) &tt, sizeof(tt), 1, input)) 

            /* Read & Display Timestamp Information */

            {

                  ++count;

 

                  cout << "********** ********** TIMESTAMP & ETHERNET FRAME ********** ***********" << endl;

                  cout << " Packet Number: " << count << endl;  /* Display Packet Number */

                  cout << " The Packets  are Captured in : " << tt.tv_sec << " Seconds" << endl;

                  cout << "The Packets  are Captured in : " << tt.tv_usec << " Micro-seconds" << endl;

 

                  /* Use caplen to Find the Remaining Data Segment */

                  cout << "The Actual Packet Length: " << tt.caplen << "Bytes" << endl; 

                  cout << "Packet Length (Off Wire): " << tt.len <<  "Bytes" << endl;

                                   

                  fread((char *) &eth, sizeof(eth), 1, input); /* Read & display ethernet header information */

                  cout << "Ethernet Header Length  : " << sizeof(eth) << " bytes" << endl;

                 

                  // You may want to remove the  MAC Address output in your code

                  printf("MAC Destination Address     : [hex] %x :%x :%x :%x :%x :%x \n\t\t\t  [dec] %d :%d :%d :%d :%d :%d\n",

                        eth.edst[0], eth.edst[1],

                        eth.edst[2], eth.edst[3], eth.edst[4], eth.edst[5], eth.edst[0], eth.edst[1],

                        eth.edst[2], eth.edst[3], eth.edst[4], eth.edst[5], eth.edst[6]);

 

                  printf("MAC Source Address    : [hex] %x :%x :%x :%x :%x :%x \n\t\t\t  [dec] %d :%d :%d :%d :%d :%d\n",

                        eth.esrc[0], eth.esrc[1], eth.esrc[2],

                        eth.esrc[3], eth.esrc[4], eth.esrc[5], eth.esrc[0], eth.esrc[1],

                        eth.esrc[2], eth.esrc[3], eth.esrc[4], eth.esrc[5]);

                 

                  printf("\n\n C Cout\n\n");

                  cout << "MAC Address " << eth.esrc[0] << " " << eth.esrc[1] << endl;

 

                  for (i=0;i<tt.caplen -14;i++)

                   { fread((char *) &buff, sizeof(buff), 1 , input);

                            printf(" %x", buff); // you may remove the printf line if neccessary

                            array[i] = buff;

             }

/*complete the code here

            

         Use the software  wireshark and capture a few packets from the live network and save the filename as abc.txt

and modify the program to display only TCP/IP packets, even modify further for the code to capture this packets from a live network. That it!!!!!

 */

 

            

             printf("\n ");

         

            } // end while

      } // end main else

 

 

      fclose(input); // Close input file

           

      return (0);

}

Reply | Email | Modify 
thanks by bunny On March 19, 2010
Thanks for the article
Reply | Email | Modify 
Failed to adapter ..All adapters are showing failed when application start... by sudheer On May 19, 2010
Failed get adapter in my PC any fix i need to do before starting.
Reply | Email | Modify 
for pacanal. packet sniffer in c#. by dulari On September 28, 2011
When I am running the program it gives an error of My class.dll. Otherwise program is superb. Please................. reply as early as possible If possible please send me the ans on dulari.bos@gmail.com
Reply | Email | Modify 
error in downloading MyClasses.dll by dulari On September 28, 2011
Download not available The following download is not available: https://rapidshare.com/files/97792934/MyClasses.dll | 0.00 MB The file of the above link no longer exists. This could be for several reasons: The uploader deleted the file. The file contained illegal contents and was deleted from our servers by our abuse-team. The file is incorrect. The server is busy and can not process the request.
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.