我正在开发 C# 代码,它使用 ARP 请求对子网(从 1-255)中的所有主机执行 ping 操作(有趣的是有多少设备响应 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());
}
}
}
关于c# - 线程 ARP ping,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22245938/