Check if a port is open

Viewed 91589

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...

private void ScanPort()
{
    string hostname = "localhost";
    int portno = 9081;
    IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];
    try
    {
        System.Net.Sockets.Socket sock =
                new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork,
                                              System.Net.Sockets.SocketType.Stream,
                                              System.Net.Sockets.ProtocolType.Tcp);
        sock.Connect(ipa, portno);
        if (sock.Connected == true) // Port is in use and connection is successful
            MessageBox.Show("Port is Closed");
        sock.Close();
    }
    catch (System.Net.Sockets.SocketException ex)
    {
        if (ex.ErrorCode == 10061) // Port is unused and could not establish connection 
            MessageBox.Show("Port is Open!");
        else
            MessageBox.Show(ex.Message);
    }
}
11 Answers

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.

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

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!

also you can use ConnectAsync like

public async Task<bool> IsIPAndPortOpen(string hostOrIPAddress, int port, TimeSpan timeOut)
        {
            try
            {
                using (var client = new TcpClient())
                {
                    var ct = new CancellationTokenSource(timeOut).Token;
                    await client.ConnectAsync(hostOrIPAddress, port, ct);
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }
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;
        }

If it is Router the simplest way to check it through online services like

You can also try using telenet to chek wether port is accessible or not

telenet [ip-address] [port] 
Related