Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send TCP packet in C#

Tags:

c#

tcp

I want to send a TCP packet (with a custom header) in C#. The building of such packets is no problem, and I have the data in a byte array. But how can I send this packet over a socket?

I tried something like this:

using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.IP))
{
    TcpPacket tcpPacket = new TcpPacket();
    // fill tcpPacket with data
    sock.Bind(new IPEndPoint(MYADDRESS, MYPORT));
    byte[] data = tcpPacket.GetBytes();
    sock.SendTo(data, new IPEndPoint(DESTADDRESS, DESTPORT));
}

This runs without any exception but sniffing the network shows that nothing is send. What is the solution?

I use Windows 7 Professional, and I don't want the system to create the full TCP connection all alone.

PS: I don't want to use some other library.

PS: Building IP packets is not a problem, either.

like image 318
ordag Avatar asked May 19 '26 01:05

ordag


1 Answers

For sending your own crafted TCP packet on Windows 7, you will need a driver like WinPcap. If you use WinPcap, you can use one of the many .NET wrappers or code your own. Sending a raw frame only with objects provided by the Windows API (like sockets) will not work.

Just look in TCP/IP Raw Sockets.

The only alternative would be to create your own network monitoring driver, or to buy a commercial version of WinPcap which does not require installation but integrates seamlessly into your program.

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

TCP data cannot be sent over raw sockets.

For the case you change your mind. Maybe you can find something you need in the library eExNetworkLibrary.

It includes a WinPcap wrapper and a lot of methods and objects to craft and analyze packets. May it will be useful.

like image 89
Emiswelt Avatar answered May 21 '26 14:05

Emiswelt



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!