我正在构建一个ping我网络中所有地址的函数。我将超时设置为15毫秒,但每次ping响应大约需要4到6秒。想象一下,4到6秒循环254次。你花了半个小时才完成广播ping。
更糟糕的是,当它到达设备占用的地址时,它会卡住!该计划不能继续前进。没有更多的调试信息。
我尝试在cmd for /l %i in (2,1,255) do ping 192.168.137.%i -n 1 -w 15 | find /I "TTL"
中手动输入for循环命令,所有过程所需的时间不会超过2分钟。
*所有这些都在子线程下,所以它不会阻止主程序。
public IPAddress[] GetAllConnectedAddressInVirtualNetwork () {
List<IPAddress> ipList = new List<IPAddress> ();
string networkAddress = GetHotspotDefaultAddress (); //e.g. 192.168.137.1
string networkPrefix = networkAddress.Substring (0, networkAddress.Length - 1); //e.g. 192.168.137.
UnityEngine.Debug.Log("Start scanning in "+networkPrefix+"x");
//Scanning from x.x.x.2 to x.x.x.255
for (int i = 2; i <= 255; i++) {
System.Net.NetworkInformation.Ping pingSender = new System.Net.NetworkInformation.Ping ();
PingReply pingReply = pingSender.Send (networkPrefix + i.ToString (), pingTimeout, Encoding.Default.GetBytes(""));
if (pingReply.Status == IPStatus.Success) {
ipList.Add (pingReply.Address);
UnityEngine.Debug.Log (pingReply.Address.ToString () + " added to list.");
} else {
UnityEngine.Debug.LogError (pingReply.Status.ToString ());
}
UnityEngine.Debug.Log ("pinged to "+networkPrefix + i.ToString ());
}
return ipList.ToArray();
}