我正在尝试使用TcpClient
列出本地网络中所有具有某个特定端口可监听的IP地址。
我的代码无法正常工作,但问题是它非常慢并且阻止了UI的执行。我需要一个可以列出ip地址并可以每秒刷新一次(如果可能的话,更好)的代码。
这是我尝试过的:
public void Start()
{
StartCoroutine(ScanNetwork());
}
IEnumerator ScanNetwork()
{
while (true)
{
yield return new WaitForSeconds(1);
for (int i = 0; i < 254; i++)
{
string address = "192.168.1." + i;
TcpClient client = new TcpClient();
if (client.ConnectAsync(IPAddress.Parse(address), GameManager.PORT).Wait(5))
{
Debug.Log("Success @" + address);
}
client.Dispose();
}
}
}
答案 0 :(得分:1)
我做了这样的事情,你可以尝试一下:
private static void ScanNetwork(int port)
{
string GetAddress(string subnet, int i)
{
return new StringBuilder(subnet).Append(i).ToString();
}
Parallel.For(0, 254, async i =>
{
string address = GetAddress("192.168.1.", i);
using (var client = new TcpClient())
{
try
{
await client.ConnectAsync(IPAddress.Parse(address), port).ConfigureAwait(false);
await Task.Delay(5).ConfigureAwait(false);
if (!client.Connected) return;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Success @{address}");
client.Close();
}
catch (SocketException ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Failed @{address} Error code: {ex.ErrorCode}");
}
}
});
}