Question

I am trying to send an ICMP AddressMask request to my router in C#. However, my socket always time out, or, if the timeout isn't set, makes the application loop indefinitely. Here is the code:

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);

I know that many types of router do not respond to an address mask request, but I tried even with a simple Echo-Request and the result was the same.

Was it helpful?

Solution

You should start with downloading Wireshark, this will allow you to see whether a response is actually being send (and whether your request is being send).

With regards to the fact that a ping does not respond, somebody else had the same problem.

This code specifically might be having issues with the way C# handles bitwise operations, you have to be very carefull there because a Byte is always signed and often upgraded to an int which causes all sorts of unexpected results.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top