简体   繁体   中英

c# Checking whether a port is actively listening?

I use the following piece of code to achieve this goal:

    public static bool IsServerListening()
    {
        var endpoint = new IPEndPoint(IPAddress.Parse("201.212.1.167"), 2593);
        var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        try
        {
            socket.Connect(endpoint, TimeSpan.FromSeconds(5));
            return true;
        }
        catch (SocketException exception)
        {
            if (exception.SocketErrorCode == SocketError.TimedOut)
            {
                Logging.Log.Warn("Timeout while connecting to UO server game port.", exception);
            }
            else
            {
                Logging.Log.Error("Exception while connecting to UO server game port.", exception);
            }

            return false;
        }
        catch (Exception exception)
        {
            Logging.Log.Error("Exception while connecting to UO server game port.", exception);
            return false;
        }
        finally
        {
            socket.Close();
        }
    }

Here is my extension method to the Socket class:

public static class SocketExtensions
{
    public const int CONNECTION_TIMEOUT_ERROR = 10060;

    /// <summary>
    /// Connects the specified socket.
    /// </summary>
    /// <param name="socket">The socket.</param>
    /// <param name="endpoint">The IP endpoint.</param>
    /// <param name="timeout">The connection timeout interval.</param>
    public static void Connect(this Socket socket, EndPoint endpoint, TimeSpan timeout)
    {
        var result = socket.BeginConnect(endpoint, null, null);

        bool success = result.AsyncWaitHandle.WaitOne(timeout, true);
        if (!success)
        {
            socket.Close();
            throw new SocketException(CONNECTION_TIMEOUT_ERROR); // Connection timed out.
        }
    }
}

The problem is this piece of code works on my development environment but when I move it into production environment it always times out (regardless of whether I set the timeout interval to 5 or 20 seconds)

Is there some other way I could check if that IP is actively listening at that particular port?

What is the reason why I can't do this from my hosting environment?

You can run netstat -na from command line to see all (including listening) ports.

If you add -b you will also see linked executable to each connection/listening.

In .NET you can get all listening connections with System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners()

You can check it by using this code:

       TcpClient tc = new TcpClient();
       try
       {

           tc.Connect(<server ipaddress>, <port number>);
           bool stat = tc.Connected;
           if (stat)
               MessageBox.Show("Connectivity to server available."); 

           tc.Close();
       }
       catch(Exception ex)
       {
           MessageBox.Show("Not able to connect : " + ex.Message);
           tc.Close();
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM