1 Attachment(s)
Simple Packet Sniffer Source
This is old, but maybe useful example of packet sniffer application written on C#
Author defines a structure using struct to store IP header in it.
Code:
[StructLayout(LayoutKind.Explicit)]
public struct IpHeader
{
[FieldOffset(0)] 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
}
StructLayoutAttribute attribute has been used to arrange the members of this structure in the necessary positions.
After that a socket using the Socket class has been created:
Code:
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.
Author put first parameter of IOControl to SIO_RCVALL(0x98000001). After packets have been received, they should be analyzed.
Author calculates length of the data in packets as follows: "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"