简体   繁体   中英

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.

PS: 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..

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM