在 C# 中发送 TCP 数据包 [英] Send TCP packet in C#

查看:47
本文介绍了在 C# 中发送 TCP 数据包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 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?

我尝试过这样的事情:

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?

我使用 Windows 7 Professional,并且我不希望系统单独创建完整的 TCP 连接.

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

PS:我不想使用其他库.

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

PS:构建 IP 数据包也不是问题.

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

推荐答案

为了在 Windows 7 上发送你自己制作的 TCP 数据包,你需要一个像 WinPcap.如果您使用 WinPcap,您可以使用众多 .NET 包装器之一或您自己的代码.仅使用 Windows API 提供的对象(如套接字)发送原始帧将不起作用.

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.

只需查看TCP/IP Raw套接字.

唯一的选择是创建您自己的网络监控驱动程序,或者购买不需要安装但可以无缝集成到您的程序中的商业版本的 WinPcap.

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.

在 Windows 7、Windows Vista、带有 Service Pack 2 (SP2) 的 Windows XP 和带有 Service Pack 3 (SP3) 的 Windows XP 上,通过原始套接字发送流量的能力受到了多种限制:

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 数据不能通过原始套接字发送.

TCP data cannot be sent over raw sockets.

对于您改变主意的情况.也许你可以在图书馆 eExNetworkLibrary 中找到你需要的东西.

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

它包括一个 WinPcap 包装器和许多用于制作和分析数据包的方法和对象.可能会有用.

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

这篇关于在 C# 中发送 TCP 数据包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆