我正在尝试向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,结果是一样的。
答案 0 :(得分:2)
您应该从下载Wireshark开始,这将允许您查看是否实际发送了响应(以及您的请求是否正在发送)。
关于ping没有响应的事实,其他人有the same problem。
这段代码可能会遇到C#处理按位操作的问题,你必须非常小心,因为Byte
总是被签名并经常升级为int,这会导致各种意外结果。< / p>