C# Raw Sockets Port Forwarding

11,831

Solution 1

sock = new Socket( AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP );
sock.Bind( new IPEndPoint( IPAddress.Parse( "10.25.2.148" ), 0 ) );
sock.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.HeaderIncluded, 1 );   
byte[] trueBytes = new byte[] { 1, 0, 0, 0 };
byte[] outBytes = new byte[] { 0, 0, 0, 0 };
sock.IOControl( IOControlCode.ReceiveAll, trueBytes, outBytes );
sock.BeginReceive( data, 0, data.Length, SocketFlags.None, new AsyncCallback( OnReceive ), null );

The only problem is that I've been able to successfully receive data from a raw socket like this, (including the IP header) but not send it.

Solution 2

Newer versions of windows restrict the use of raw sockets due to malware heavily abusing them.

Quoted from the MSDN

On Windows 7, Windows Vista, and Windows XP with Service Pack 2 (SP2), the ability to send traffic over raw sockets has been restricted in several ways:

  • TCP data cannot be sent over raw sockets.
  • UDP datagrams with an invalid source address cannot be sent over raw sockets. The IP source address for any outgoing UDP datagram must exist on a network interface or the datagram is dropped. This change was made to limit the ability of malicious code to create distributed denial-of-service attacks and limits the ability to send spoofed packets (TCP/IP packets with a forged source IP address).
  • A call to the bind function with a raw socket for the IPPROTO_TCP protocol is not allowed. Note The bind function with a raw socket is allowed for other protocols (IPPROTO_IP, IPPROTO_UDP, or IPPROTO_SCTP, for example.

These above restrictions do not apply to Windows Server 2008 R2, Windows Server 2008 , Windows Server 2003, or to versions of the operating system earlier than Windows XP with SP2.

Share:
11,831
Superman
Author by

Superman

Updated on June 04, 2022

Comments

  • Superman
    Superman almost 2 years

    I am trying to create a simple C# app which does port forwarding, and need to know how to use the IP_HDRINCL socket option to try to fake out the receiving end to think the connection is really to the source. Any examples would be greatly appreciated.

  • Benj Sanders
    Benj Sanders over 8 years
    Let me save you some time. The code mentioned here has mal-referenced methods and does not compile. Don't wast your time here :)