Deathspike
Deathspike

Reputation: 8770

Reading incoming packets using a raw socket on IP protocol in C#

I'm trying to read incoming packets on a raw socket with headers enabled. Looking at other projects, such as MJsniffer on CodeProject I've been able to create my own code to read everything I want. The problem: I'm only retrieving information that is OUTGOING. Here's my code to initialize a raw socket, the processing code is irrelevant at this point..

// Resolve the host name or IP address to am IPHostEntry instance
IPHostEntry hIPHostEntry = Dns.GetHostEntry( Dns.GetHostName());

// Initialize a new instance of the Socket class.
Socket hSocket = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Unspecified ); // IP is possible.

// Bind the socket to each resolved IP address.
foreach ( IPAddress hIPAddress in hIPHostEntry.AddressList ) try { hSocket.Bind( new IPEndPoint( hIPAddress, 0 )); } catch( Exception ) { continue; }

// Configure the incoming socket to accept all the required information.
hSocket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, true );

// Configure the incoming socket to receive all the required information.
hSocket.IOControl( IOControlCode.ReceiveAll, BitConverter.GetBytes( 1 ), BitConverter.GetBytes( 1 ));

// Return the configured socket.
return hSocket;

Running on Windows 7 64-Bit, I have full Administrative rights, how can I modify this code to get a socket able to read incoming packets? Outgoing is nice, and I need that too, but I absolutely need incoming packets as well.

P.S: I don't want to force users to install WinPcap. I don't want to capture or spoof or anything, just read, this SHOULD be possible..

Upvotes: 3

Views: 4693

Answers (2)

Bitwise
Bitwise

Reputation: 111

This may no longer help you, but for anyone else:

After spending too much time looking at this myself, I ran the executable by itself instead of through Visual Studio. Incoming traffic, amazing! I then added the VS debug .exe (MJSniff.vshost.exe) to the allowed programs in my firewall and that works now as well. (It's always the simple things...)

Edit: credit also to an answer here by Joe Mattioni: Unable to read incoming responses using raw sockets

Upvotes: 2

Coincoin
Coincoin

Reputation: 28586

For debugging purposes, have you tried binding to IPAddress.Any instead? This way, you will have one single binding to all local interfaces.

Also, are you using Receive() or ReceiveFrom(), it should be ReceivedFrom() for connectionless sockets.

Upvotes: 0

Related Questions