如何使用 TcpClient 查找局域网中的所有 ip 地址

How to find all ip adresses in Lan using TcpClient

我正在尝试使用 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();
            }
        }
    }

我做了这样的事情你能试试吗:

    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}");
                }
            }
        });
    }