Click here to Skip to main content
15,671,597 members
Articles / Programming Languages / C#
Posted 11 Sep 2004


266 bookmarked

Network Sniffer and Connection Analyzer

Rate me:
Please Sign up or sign in to vote.
4.42/5 (64 votes)
30 Jan 20057 min read
Network sniffer and connection analyzer.

Sample Image - HSSniffer.jpg


Project is an implementation of a Packet Sniffer that captures packet in a LAN environment using Microsoft .NET environment and written in C#.

Our goal was to build a network utility tool that can be an assistant to programmers, network managers, and private users. Our Sniffer can be useful for monitoring traffic, debugging, fault analysis, network protocol analysis, network intrusion detection, traffic measuring etc.

In order to reach our goals, project supplies some useful features that can be easily used. Features can be summarized like this:

  • Organize captured packets in a connection-oriented view.
  • Smart real-time analyzer enables on-the-fly content viewing while capturing and analyzing.
  • Parse and decode an variety of network protocol.
  • Protocol definition tool to extend protocols that are decodable.
  • Powerful filter provides a flexible mechanism to capture specific packets.
  • Port Scanner utility.
  • Finds process that uses each connection.
  • Syntax highlighting for application data.

We did not use any capture library; instead we wrote our own capture library and build a GUI that serve user an easy interface. To build capture library we used .NET network classes that provide interface to native Winsock API and asynchronous sockets that brings thread based solution to socket programming.

Project Files (Sniffer)


Class “consts” contain some functions returning string equivalents of protocol field values.


Class “DataManager” holds IP datagrams in hash data collection. In order to provide uniqueness it produces a key to every packet and supply adding removing functions that operate on its hash table.


We need to resolve domain names of Ips and this process requires too much time and cause a performance bottlenecks. We overwhelm this problem with building this class that stores resolved domain names in a hash table and serve a function GetName function that first look up IP in its table to resolve its domain name. If this domain name of Ip could not be resolved then request it from a domain name server.


Supply filtering functionality. FilterManager has a container that contains filter items and adding removing functions that allow adding removing filters to its filter container. Most important function FilterManager supplied is isAllowed. This function determines whether packet is to be discarded.


This supply a helper class that extract field values from Ip Datagram.


Define a class that used to set fields of an ICMP packet or extract these fields’ values from IP datagram.

Icmp packets do not have a fixed format. First four bytes are same for all types of Icmp packets, so decoding these packets has some difficulties. We overwhelmed this problem by after decoding type and code values, extract other fields according to these fields. CheckNextFields function is doing that.

getBytes function produces a raw byte array that is put in a form that is ready to send though socket.

There is no need to mention to other functions.


IPv4Datagram class extracts all fields of an Ip datagram. If fragmented, store fragments and when all fragments reach, build the original packet. In addition, class includes functions to handle TCP, UDP, ICMP packets.


Protocols class is a static class that stores protocol definitions in a container. First time when this class is accessed, it reads all protocol definition from XML files.

This class contains functions supplied operations to read parse XML data.


This class extracts fields of a packet according to protocol definitions that are loaded from XML files.

First, we obtain what type of template packet will be build by looking up to Ip datagrams next header section and loads its definition from Protocols class and set its fields by using SetFields function that ProtocolTemplate class provides us.


Contain exception class that will be thrown when a problem arises during sniffing.


This file contains core class that builds our Packet Sniffer. It brings an event driven solution to sniffing. We explain it important functions below.

Sniff: creates a socket and binds it to the ip that is supplied, setup socket to receive all packets, begin capturing packets asynchronously.

SetupSocket: put socket in receiving all packets mode.

ReceivePacket: It is called whenever asynchronous Soket.BeginReceive operation is completed and calls itself to keep on receiving packets.

HandleIPv4Datagram: called from ReceivePacket if captured packet is an IPv4 datagram and fires create an IPv4Datagram and fire IPv4DatagramReceived events.


Class that contains a socket handle and a buffer that belongs to this socket.


Class that decodes fields of an incoming TCP Packet.


This is a helper class used to group Source IP, Destination IP, Source Port, Destination Port, Protocol Number and its string counterpart into a class. We use it to pass all these values in a single structure.


Class that decodes fields of an incoming UDP Packet.

Project Files (SnifferUI)


Class that holds Ip addresses in a container. We use update Ip address list that is being listening.


This class serve as an interface to add new protocols to Sniffer’s protocol list.


This class is used to get an IP from user.


This form is a common interface used by ping, trace route and connection checker. Result of the operation reported is to the user in this form.


This is a static class and has functions that are Ping, Trace Route and Check. These functions are called from CheckerForm class’s on load function and given to a thread to not to block other operations.

Ping and TraceRoute operate like original ping and Tracert network utilities but Check is a bit different, first trace path to the remote host and if it can not obtain any response from it, scans a few ports of it that are likely to be in listening state. Such a way it tries to determine if that host entry is alive.


This class creates filter and adds it to Sniffer’s FilterManager.


This class contains functions that used to manage Sniffer’s FilterManager. Here some functions are supplied to add, remove filters and change the order of filters.


This is a limited version of ICMP that is used by CheckTool.cs.


This is a class that extends the System.Windows.Form.UserControl class. When HandleIcmpPacket is function fired, it is added to the Packet View.


This class interfaces the IpHlpApidotnet.IPHelper class. We did not implement IpHlpApidotnet.IPHelper, we only use it and transfer the results of it to list view.

IpHlpApidotnet.IPHelper is a wrapper class that uses IpHlpApi.dll and gets tables of inbound and outbound network connections, including the information on open TCP and UDP ports, IP address, and connection states. What makes it different from other NetStat utilities is the ability to map open ports to the owning application.


This is a user control class that uses ProtocolTemplate class and handles dynamically added protocols in user interface.


This is the static class that holds the settings of tool that are Ping, Trace Route and Connection Checker. These settings related to the protocol type of the outgoing packets that send by mentioned tools.


This class provides the interface to let user to change settings.


This class is the core of the interface.


This class provides two functions that are getProcessId and getProcessName. Using these two functions we relate connection to its owning process.


This is a class that extends the System.Windows.Form.UserControl class. When HandleTcpPacket function is fired, it is added to the Packet View.


This class enables viewing decoded packets in tree view. Another feature that provided is, highlighting text in Hexadecimal and Binary Views when user selects a field in tree view.


This is a class that extends the System.Windows.Form.UserControl class. When HandlUdpPacket function fired, it is added to the Packet View.

Project Files (PortScanner)


Parses and extracts configuration data from XML file. This configuration includes the following.

Which servers with which port will be scanned, mail server that will be used, sender of the mails, receiver that will be notified, loop count for scan process and time interval between scans.


Creates an interface that ease making XML files configurations.


This class enables creation of event log and writing of log.


This class enables view of ListViewItems in detail.


This is the core class that scans ports, enables user to control port scanner.


Saves and loads PortScanner’s settings from XML file. Setting has the file name whose default configuration to be loaded.


This file enables setting configuration file.


SMTP class has functions that enable sending mail.


Provides two functions that are getFileLastModifiedTime and isFileExist.

Here is the our implementation of asynchronous functions.

public void Sniff(String ip) 
Socket socket = new Socket(AddressFamily.InterNetwork,
byte[] buffer = new byte[2048];
SocketPair socketpair = new SocketPair(socket,buffer);
socket.Blocking = true;
   socket.Bind(new IPEndPoint(IPAddress.Parse(ip),0));
catch(SocketException e)
   throw new SnifferException("Cannot assign requested address.The 
requested address is not valid in its context.",e);
if ( SocketMap_.Contains(ip) ) 
   throw new SnifferException("Socket already bound on that IP");
{           socket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,new 
catch ( Exception e ) 
   throw new SnifferException("Could not start the Receive",e);
// Callback function for the Asynchronous Receive on a Socket.
private void ReceivePacket(IAsyncResult ar) 
bool fired=false;
int len = 0;
SocketPair p = ar.AsyncState as SocketPair;
Socket socket = p.IPSocket;
int type = 0;
   len = socket.EndReceive(ar);
catch ( SocketException e) 
   fired = true;
   FireSnifferError(new SnifferException("Error Receiving 
if (!fired)
   type = HeaderParser.ToInt(p.Buffer,0,4);
          case 4:
   catch ( Exception e ) 
if (!this.paused)
.None,new AsyncCallback(this.ReceivePacket),p);


This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

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

Comments and Discussions

QuestionCross thread operation Pin
el_tel11-Aug-15 0:08
el_tel11-Aug-15 0:08 
Questionmay i know how to run this code Pin
Member 1079163112-May-14 20:15
Member 1079163112-May-14 20:15 
QuestionDocumentation and Cross thread operation not valid Pin
kunteshptechnosoft7-Jan-14 18:58
professionalkunteshptechnosoft7-Jan-14 18:58 
QuestionWork with Wifi Pin
jchero.sojo17-May-13 9:25
professionaljchero.sojo17-May-13 9:25 
Questionhow to run project Pin
Hamsasheela Sheela7-Mar-13 16:18
Hamsasheela Sheela7-Mar-13 16:18 
Questionhow to correct this error Pin
nithyavinotha5-Jan-13 14:45
nithyavinotha5-Jan-13 14:45 
AnswerRe: how to correct this error Pin
jchero.sojo17-May-13 9:29
professionaljchero.sojo17-May-13 9:29 
QuestionNetwork problems Pin
AJMAL SHAHZAD10-Dec-12 18:50
AJMAL SHAHZAD10-Dec-12 18:50 
Questionrunning sniferUI Pin
sogolii14-Sep-12 6:02
sogolii14-Sep-12 6:02 
Questionvote 5 Pin
boris.pong18-Jun-12 21:49
boris.pong18-Jun-12 21:49 
good work!Thumbs Up | :thumbsup:
QuestionPlz help...Its please.. Pin
Member 901043321-May-12 23:05
Member 901043321-May-12 23:05 
Questionhelp me Pin
Belalkoochaki12-May-12 5:08
Belalkoochaki12-May-12 5:08 
Questioncode for network sniffer Pin
p_oonam27-Mar-12 6:15
p_oonam27-Mar-12 6:15 
QuestionRegarding Project Run Pin
ashishs173510-Mar-12 17:16
ashishs173510-Mar-12 17:16 
QuestionCan u provide the Documentation for this Project ? Pin
Member 84434032-Dec-11 2:54
Member 84434032-Dec-11 2:54 
Generaltry execute source in win 2000\nt Pin
Anil D S5-Jan-11 20:54
Anil D S5-Jan-11 20:54 
Generalproblem Pin
amir_amir_amir19-Sep-10 8:41
amir_amir_amir19-Sep-10 8:41 
GeneralRe: problem Pin
Sasha Grigorovich2-Jun-22 9:43
Sasha Grigorovich2-Jun-22 9:43 
GeneralIts very urgent!!! Pin
shubhanshu1216-Apr-10 17:36
shubhanshu1216-Apr-10 17:36 
GeneralProject will not compile with Visual Studio 2008 Professional C# Pin
spicture15-Feb-10 8:47
spicture15-Feb-10 8:47 
GeneralRe: Project will not compile with Visual Studio 2008 Professional C# Pin
sainulabi1-Jun-10 20:04
sainulabi1-Jun-10 20:04 
GeneralRe: Project will not compile with Visual Studio 2008 Professional C# Pin
dragonblue050219894-May-11 23:21
dragonblue050219894-May-11 23:21 
Generalwinsock tools for server 2008 Pin
Member 143923410-Jan-10 17:28
Member 143923410-Jan-10 17:28 
Generaldoubt Pin
shubhanshu12110-Jan-10 3:40
shubhanshu12110-Jan-10 3:40 
GeneralError Pin
abdallah2223339-Dec-09 22:14
abdallah2223339-Dec-09 22:14 

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.