我正在开发C#代码,该代码pings pings pings pings pings pings pings pings ping ping(从1-255起)带有ARP请求(有趣的是有多少设备对ARP请求响应,但没有ping)。>
使用ping我可以设置超时并运行异步,并且需要一秒钟才能扫描子网。我不确定如何使用ARP执行此操作,因为我无法设置超时值。我可以在线程中发送请求吗?我在多线程方面几乎没有经验,但是欢迎任何帮助。
[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
}
这应该做到。自然,控制台输出可能不会订购。
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());
}
}
}