Click here to Skip to main content
Click here to Skip to main content

Network Sniffer and Connection Analyzer

, 30 Jan 2005
Rate this:
Please Sign up or sign in to vote.
Network sniffer and connection analyzer.

Sample Image - HSSniffer.jpg

Introduction

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)

Consts.cs

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

DataManager.cs

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.

DnsTable.cs

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.

FilterManager.cs

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.

HeaderParser.cs

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

IcmpPacket.cs

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

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

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.

ProtocolTemplate.cs

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.

SnifferException.cs

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

SnifferSocket.cs

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.

SocketPair.cs

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

TcpPacket.cs

Class that decodes fields of an incoming TCP Packet.

trio.cs

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.

UdpPacket.cs

Class that decodes fields of an incoming UDP Packet.

Project Files (SnifferUI)

AddIP.cs

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

AddProtocols.cs

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

AddressInput.cs

This class is used to get an IP from user.

CheckerForm.cs

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.

CheckTool.cs

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.

FilterCreater.cs

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

Filtering.cs

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.

Icmp.cs

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

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

NetStat.cs

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.

OtherProtocols.cs

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

Setting.cs

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.

Settings.cs

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

SnifferUI.cs

This class is the core of the interface.

tablesForProc.cs

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

tcpView.cs

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

treeViewFuncs.cs

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.

udpView.cs

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)

Configuration.cs

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.

CreateFileForm.cs

Creates an interface that ease making XML files configurations.

Logging.cs

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

LogItemView.cs

This class enables view of ListViewItems in detail.

PortScanner.cs

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

Setting.cs

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

SettingForm.cs

This file enables setting configuration file.

Smtp.cs

SMTP class has functions that enable sending mail.

Utility.cs

Provides two functions that are getFileLastModifiedTime and isFileExist.

Here is the our implementation of asynchronous functions.

public void Sniff(String ip) 
{
IP=ip;
Socket socket = new Socket(AddressFamily.InterNetwork,
 SocketType.Raw,ProtocolType.IP);
byte[] buffer = new byte[2048];
SocketPair socketpair = new SocketPair(socket,buffer);
socket.Blocking = true;
try
{
   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);
}
this.SetupSocket(socket);
           
if ( SocketMap_.Contains(ip) ) 
{ 
   throw new SnifferException("Socket already bound on that IP");
} 
else 
{ 
   SocketMap_.Add(ip,socketpair);
}
try 
{           socket.BeginReceive(buffer,0,buffer.Length,SocketFlags.None,new 
AsyncCallback(this.ReceivePacket),socketpair);
   paused=false;
} 
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;
try 
{ 
   len = socket.EndReceive(ar);
} 
catch ( SocketException e) 
{ 
   fired = true;
   FireSnifferError(new SnifferException("Error Receiving 
Packet",e));
}
if (!fired)
{
   type = HeaderParser.ToInt(p.Buffer,0,4);
   try 
   { 
        switch(type) 
    { 
          case 4:
           HandleIPv4Datagram(p.Buffer);
           break;
    }
   } 
   catch ( Exception e ) 
   {
    FireSnifferError(new
SnifferException(e.Message.ToString(),e));
   }
}
if (!this.paused)
{
  socket.BeginReceive(p.Buffer,0,p.Buffer.Length,SocketFlags
.None,new AsyncCallback(this.ReceivePacket),p);
}
}

License

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

About the Author

syanar
Web Developer
Turkey Turkey
No Biography provided

Comments and Discussions

 
Questionmay i know how to run this code PinmemberMember 1079163112-May-14 20:15 
QuestionDocumentation and Cross thread operation not valid PinprofessionalMember 105100007-Jan-14 18:58 
QuestionWork with Wifi Pinprofessionaljchero.sojo17-May-13 9:25 
Questionhow to run project PinmemberHamsasheela Sheela7-Mar-13 16:18 
Questionhow to correct this error Pinmembernithyavinotha5-Jan-13 14:45 
AnswerRe: how to correct this error Pinprofessionaljchero.sojo17-May-13 9:29 
QuestionNetwork problems PinmemberAJMAL SHAHZAD10-Dec-12 18:50 
Questionrunning sniferUI Pinmembersogolii14-Sep-12 6:02 
Questionvote 5 Pinmemberboris.pong18-Jun-12 21:49 
QuestionPlz help...Its urgent...so please.. PinmemberMember 901043321-May-12 23:05 
Questionhelp me PinmemberBelalkoochaki12-May-12 5:08 
Questioncode for network sniffer Pinmemberp_oonam27-Mar-12 6:15 
QuestionRegarding Project Run Pinmemberashishs173510-Mar-12 17:16 
QuestionCan u provide the Documentation for this Project ? PinmemberMember 84434032-Dec-11 2:54 
Generaltry execute source in win 2000\nt PinmemberAnil D S5-Jan-11 20:54 
Generalproblem Pinmemberamir_amir_amir19-Sep-10 8:41 
GeneralIts very urgent!!! Pinmembershubhanshu1216-Apr-10 17:36 
GeneralProject will not compile with Visual Studio 2008 Professional C# Pinmemberspicture15-Feb-10 8:47 
GeneralRe: Project will not compile with Visual Studio 2008 Professional C# Pinmembersainulabi1-Jun-10 20:04 
GeneralRe: Project will not compile with Visual Studio 2008 Professional C# Pinmemberdragonblue050219894-May-11 23:21 
Generalwinsock tools for server 2008 PinmemberMember 143923410-Jan-10 17:28 
Generaldoubt Pinmembershubhanshu12110-Jan-10 3:40 
GeneralError Pinmemberabdallah2223339-Dec-09 22:14 
QuestionHow to run it Pinmemberhunzabasharat16-Oct-09 20:55 
AnswerRe: How to run it PinmemberAnkur_Mundhra16-Jan-10 1:36 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 30 Jan 2005
Article Copyright 2004 by syanar
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid