0

I'm trying to use TcpClient to list all the ip addresses in a Local network that have a certain port open to listen.

My code bellow works but the problem is that it's very slow and blocks the execution of the UI. I need a code that can list the ip addresses and can be refreshed every second (or better if possible).

Here is what I tried:

    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();
            }
        }
    }
kyu
  • 111
  • 1
  • 10

1 Answers1

1

I did something like this can you try it :

    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}");
                }
            }
        });
    }
Shehab
  • 431
  • 2
  • 10