Check if a port is open

前端 未结 10 928
萌比男神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:15

    For me, I needed something blocking until the connection to the port is available or after a certain amount of retries. So, I figured out this code:

    public bool IsPortOpen(string host, int port, int timeout, int retry)
    {
        var retryCount = 0;
        while (retryCount < retry)
        {
            if (retryCount > 0)
                Thread.Sleep(timeout);
    
            try
            {
                using (var client = new TcpClient())
                {
                    var result = client.BeginConnect(host, port, null, null);
                    var success = result.AsyncWaitHandle.WaitOne(timeout);
                    if (success)
                        return true;
    
                    client.EndConnect(result);
                }
            }
            catch
            {
                // ignored
            }
            finally { retryCount++; }
        }
    
        return false;
    }
    

    Hope this helps!

提交回复
热议问题