ICMP套接字总是超时

本文关键字:超时 套接字 ICMP | 更新日期: 2023-09-27 18:20:22

我正在尝试向C#中的路由器发送ICMP AddressMask请求。但是,我的套接字总是超时,或者,如果没有设置超时,则会使应用程序无限期地循环。这是代码:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Raw, ProtocolType.Icmp);
socket.Bind(new IPEndPoint(interfaceAddress, 0));
Random rnd = new Random();
UInt16 seed, sn;
seed = (UInt16)rnd.Next();
sn = (UInt16)rnd.Next();
var icmpAddressMaskRequest = new Byte[12];
icmpAddressMaskRequest[0] = 17;
icmpAddressMaskRequest[4] = (Byte)(seed >> 8);
icmpAddressMaskRequest[5] = (Byte)(seed & 0xff);
icmpAddressMaskRequest[6] = (Byte)(sn >> 8);
icmpAddressMaskRequest[7] = (Byte)(sn & 0xff);
UInt16 checksum = 0;
for (int i = 0; i < 6; i++)
{
    Int32 twoOctects = icmpAddressMaskRequest[2 * i] * 256 + icmpAddressMaskRequest[2 * i + 1];
    Int32 tempChecksum = checksum + twoOctects;
    if (tempChecksum > UInt16.MaxValue)
        checksum = (UInt16)((tempChecksum & 0xffff) + 1);
    else
        checksum = (UInt16)tempChecksum;
}
icmpAddressMaskRequest[2] = (Byte)(255 - checksum >> 8);
icmpAddressMaskRequest[3] = (Byte)(255 - checksum & 0xff);
EndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.100.1"), 0);
socket.ReceiveTimeout = 2000;
socket.SendTo(icmpAddressMaskRequest, remoteEndPoint);
var buffer = new Byte[4096];
socket.ReceiveFrom(buffer, ref remoteEndPoint);

我知道很多类型的路由器都不会响应地址掩码请求,但我甚至尝试了一个简单的回声请求,结果是一样的。

ICMP套接字总是超时

您应该从下载Wireshark开始,这将允许您查看是否真的在发送响应(以及是否正在发送请求)。

关于ping没有响应的事实,其他人也有同样的问题。

特别是这段代码可能在C#处理逐位操作的方式上有问题,您必须非常小心,因为Byte总是经过签名的,并且经常升级为int,这会导致各种意外的结果。