我知道并非所有设备都响应ICMP或ping,因此最合适的方式似乎是向LAN上可能的所有IP发送ARP请求,从192.168.0.0到192.168.255.255,但这意味着请求超过65000个IP这花了很多时间.我想找到我的程序的另一个实例,以便同步他们的内容,但我不满意ARP方法.到目前为止,我在SO中找到了这些优秀的代码:
[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>();
for (int i = 0; i <= 255; i++)
{
for (int s = 0; s <= 255; s++)
{
ipAddressList.Add(IPAddress.Parse("192.168." + i + "." + s));
}
}
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());
}
}
Run Code Online (Sandbox Code Playgroud)
但正如您所看到的,ARP请求所有范围将花费很长时间.我的笔记本电脑上10到15分钟.当然,在大多数情况下,你会发现所需的IP速度要快得多,我的意思并不是说你会如此不走运,以至于PC会落在192.168.255.255左右,但仍需要几分钟.这只会做一次,因为大多数时候PC和笔记本电脑使用的优先IP会保留数天或数月,除非改变,所以只要它继续处理该IP,就不需要另外的ARP提取.到目前为止,最好的选择是第一次发生这种"热启动"并用加载屏幕进行装饰,但我想知道是否有更快的方法来实现这一点.此外,我只是在寻找Windows PC,因为它只是在同一个应用程序的实例之间.