Check if a port is open

前端 未结 10 922
萌比男神i
萌比男神i 2020-12-08 10:37

I can\'t seem to find anything that tells me if a port in my router is open or not. Is this even possible?

The code I have right now doesn\'t really seem to work...<

10条回答
  •  悲哀的现实
    2020-12-08 11:08

    Other than BeginConnect you can also use ConnectAsync (added in .NET Framework 4.5 I think?).

    TcpClient client = null;
    
    try {
        client = new TcpClient();
        var task = client.ConnectAsync(host, port);
        if (task.Wait(timeout)) {//if fails within timeout, task.Wait still returns true.
            if (client.Connected) {
                // port reachable
            }
            else
                // connection refused probably
        }
        else
            // timed out
    }
    catch (Exception ex) {
        // connection failed
    }
    finally {
        client.Close();
    }
    

    Full project is here because paping refuses to run and I couldn't find another "ping host:port" tool to my likes.

提交回复
热议问题