3

I am developing C# code that pings all hosts within a subnet (from 1-255) with ARP requests (funny how many devices responds to ARP requests, but not pinging).

With Ping I can set the timeout and run Async, and it takes a second to scan a subnet. I am not sure how I will do this with ARP, since I can't set the timeout value. Can I send requests in threads? I have little experience with multithreading, but any help is welcome.

[DllImport("iphlpapi.dll", ExactSpelling = true)]
public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint, PhyAddrLen);

...

if (SendARP(intAddress, 0, macAddr, ref macAddrLen) == 0)
{
// Host found! Woohoo
}
user3296337
  • 107
  • 10
  • checkout [this](http://stackoverflow.com/questions/8924169/how-to-ping-faster-when-i-reach-unreachable-ip) question's answer, and see if it helps or not. – Vitap Ramdevputra Mar 07 '14 at 10:09
  • It did not. It merely suggests pinging async, a functionality I already mentioned in my question. – user3296337 Mar 07 '14 at 10:44

1 Answers1

3

This should do it. Naturally the console output might not be ordered.

class Program
{
    [DllImport("iphlpapi.dll", ExactSpelling = true)]
    public static extern int SendARP(int DestIP, int SrcIP, byte[] pMacAddr, ref uint PhyAddrLen);

    static void Main(string[] args)
    {
        List<IPAddress> ipAddressList = new List<IPAddress>();

        //Generating 192.168.0.1/24 IP Range
        for (int i = 1; i < 255; i++)
        {
            //Obviously you'll want to safely parse user input to catch exceptions.
            ipAddressList.Add(IPAddress.Parse("192.168.0." + i));
        }

        foreach (IPAddress ip in ipAddressList)
        {
            Thread thread = new Thread(() => SendArpRequest(ip));
            thread.Start();

        }
    }

    static void SendArpRequest(IPAddress dst)
    {
        byte[] macAddr = new byte[6];
        uint macAddrLen = (uint)macAddr.Length;
        int uintAddress = BitConverter.ToInt32(dst.GetAddressBytes(), 0);

        if (SendARP(uintAddress, 0, macAddr, ref macAddrLen) == 0)
        {
            Console.WriteLine("{0} responded to ping", dst.ToString());
        }
    }
}
Daniel
  • 10,641
  • 12
  • 47
  • 85