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
}
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());
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With