I have a book called Network Programming in .NET which has the following code sample for sniffing IP packets on the network stack. I have copied the code sample WORD-FOR-WORD from the book so please excuse the lack of stylistic conventions etc.
List<string> packets = new List<string>();
public void Run()
{
int len_receive_buf = 4096;
int len_send_buf = 4096;
byte[] receive_buf = new byte[len_receive_buf];
byte[] send_buf = new byte[len_send_buf];
int cout_receive_bytes;
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP);
socket.Blocking = false;
IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName());
socket.Bind(new IPEndPoint(IPAddress.Parse(IPHost.AddressList[0].ToString()), 0));
socket.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1);
byte[] IN = new byte[4] { 1, 0, 0, 0 };
byte[] OUT = new byte[4];
int SIO_RCVALL = unchecked((int)0x98000001);
int ret_code = socket.IOControl(SIO_RCVALL, IN, OUT);
while(true)
{
IAsyncResult ar = socket.BeginReceive(receive_buf, 0, len_receive_buf, SocketFlags.None, null, this);
cout_receive_bytes = socket.EndReceive(ar);
Receive(receive_buf, cout_receive_bytes);
}
}
public void Receive(byte[] buf, int len)
{
if(buf[9] == 6)
{
packets.Add(Encoding.ASCII.GetString(buf).Replace("\0", " "));
}
}
The first time I tested this was a few years ago (before even Vista existed) and the machine I used was a 32bit Windows XP Proferssional platform with a NIC running on IPv4.
I am now trying to test on a 64bit Windows 7 platform with a NIC running IPv6 but its not working. I am assuming this is something to do with IPv6. Can anyone suggest how I might fix this efficiently?
EDIT: This is the exception I get when I try to run…

Headers are significantly different between IPv4 and IPv6.
So the check of:
Which checks whether the packet is TCP for IPv4 is querying part of the source address field of an IPv6 packet. For IPv6, it ought to be checking “Next Header” which is at offset 6*. Of course, now you’ll also have to check the IP version first to know whether to check offset 6 or offset 9.
For the exception message, it’s likely that you’re not running as Administrator, which you need to be to listen on raw sockets (native documentation, but still applicable):
(*) Of course, there may be multiple IPv6 headers to work through before you discover that it’s a TCP packet.