Simple Sniffer in C#

In this application, first of all I define a structure using struct to store IP header in it.

public struct IpHeader
public byte ip_verlen; // IP version and IP Header length
[FieldOffset(1)] public byte ip_tos; // Type of service
[FieldOffset(2)] public ushort ip_totallength; // total length of the packet
[FieldOffset(4)] public ushort ip_id; // unique identifier
[FieldOffset(6)] public ushort ip_offset; // flags and offset
[FieldOffset(8)] public byte ip_ttl; // Time To Live
[FieldOffset(9)] public byte ip_protocol; // protocol (TCP, UDP etc)
[FieldOffset(10)] public ushort ip_checksum; //IP Header checksum
[FieldOffset(12)] public long ip_srcaddr; //Source address
[FieldOffset(16)] public long ip_destaddr;//Destination Address

To know more about IP header read RFC791. I have used attribute StructLayoutAttribute to arrange the members of this structure in the necessary positions.

After that I create a socket using the Socket class as following:

socket =
new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);

It should be Raw socket and bind socket to defined IP And called function IOControl(it must be called after you call Bind) IOControl it's analogue of WSAIoctl API function.

I must put first parameter of  IOControl to SIO_RCVALL(0x98000001), in Platform SDK is told, that second parameter should be BOOL and should be equal TRUE. Therefore I create array {1, 0, 0, 0}.

Now we can receive packet. After we receive packet, we should analyze it.

For first need fixed packet in memory, differently GC can him transfer in memory and  get the pointer to him

fixed(byte *fixed_buf = buf)

convert pointer from byte * to IpHeader *

Ok, now we have pointer to IP header and find length, protocol, source ip, destination ip and other.

I calculated length of the data in packets as follows is "protocol header length (TCP, UDP, ICMP etc)" + "data" without length "ip header length".  Total length is "ip header length" + "protocol header length(TCP, UDP, ICMP etc)" + "data"

For TCP and UDP I calculate ports.

This program should work on Windows 2000 and Windows XP. I am not sure about Windows ME.