Check if a port is open

前端 未结 10 910
萌比男神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.

    0 讨论(0)
  • 2020-12-08 11:10
    public string GetAvailablePort()
            {int startingPort=1000;
                string portnumberinformation = string.Empty;
                IPEndPoint[] endPoints;
                List<int> portArray = new List<int>();
                IPGlobalPr`enter code here`operties properties = IPGlobalProperties.GetIPGlobalProperties();`enter code here`
    
    
                //getting active tcp listners 
                endPoints = properties.GetActiveTcpListeners();
                portArray.AddRange(from n in endPoints
                                   where n.Port >= startingPort
                                   select n.Port);    
    
                portArray.Sort();
    
                for (int i = 0; i < portArray.Count; i++)
                {
                    if (check condition)
                    {
                        do somting
                    }
                }
    
                return portnumberinformation;
            }
    
    0 讨论(0)
  • 2020-12-08 11:13

    There is no way to know if the port is forwarded in your router, except if there is a program listening on that port.

    As you may see in the Clinton answer, the .Net class being used is TcpClient and that is because you are using a TCP socket to connect to. That is the way operating systems make connections: using a socket. However, a router just forwards the packets (layer 3 of the OSI Model) in or out. In your case, what your router is doing is called: NAT. It is one public IP shared by a one or more private IPs. That´s why you are making a port forwarding.

    There may be a lot of routers in the path of the packets, and you will never know what had happened.

    Let´s imagine you are sending a letter in the traditional way. Perhaps you can write in the letter that the receiver must answer, in order to check he/she is there (you and the receiver are the sockets). If you receive an answer you will be sure he/she is there, but if you don´t receive anything you don´t know if the mailman (in your case the router) forgot to deliver the letter, or the receiver hadn´t answered. You would also never know if the mailman has asked a friend to deliver that letter. Moreover, the mailman won´t open the letter in order to know he/she may answer because you are waiting for a reply. All you may do is wait some time to receive the answer. If you don´t receive anything in that period you will assume that the receiver isn´t where you sent the letter. That is a "timeout".

    I saw an answer mentioning the nmap software. It´s really a very good and complex soft, but I think it will work in the same way. If there is no app listening in that port, there is no way to know if it is open or not.

    Please, let me know if I was clear.

    0 讨论(0)
  • 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!

    0 讨论(0)
  • 2020-12-08 11:21

    Try this:

    using(TcpClient tcpClient = new TcpClient())
    {
        try {
            tcpClient.Connect("127.0.0.1", 9081);
            Console.WriteLine("Port open");
        } catch (Exception) {
            Console.WriteLine("Port closed");
        }
    }
    

    You should probably change 127.0.0.1 to something like 192.168.0.1 or whatever your router's IP address is.

    0 讨论(0)
  • 2020-12-08 11:22
    public static bool PortInUse(int  port)
    {
        bool inUse = false;
    
        IPGlobalProperties ipProperties = IPGlobalProperties.GetIPGlobalProperties();
        IPEndPoint [] ipEndPoints = ipProperties.GetActiveTcpListeners();
    
    
        foreach(IPEndPoint endPoint in ipEndPoints)
        {
            if(endPoint.Port == port)
            {
                inUse = true;
                break;
            }
        }
    
    
        return  inUse;
    }
    
    0 讨论(0)
提交回复
热议问题