我正在尝试用 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);
我知道许多类型的路由器不会响应地址掩码请求,但我什至尝试了一个简单的 Echo-Request,结果是一样的。