简体   繁体   English

c#检查端口是否正在积极侦听?

[英]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: 这是我对Socket类的扩展方法:

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) 问题是这段代码可以在我的开发环境上工作,但是当我将其移入生产环境时,它总是会超时(无论我将超时间隔设置为5还是20秒)

Is there some other way I could check if that IP is actively listening at that particular port? 还有其他方法可以检查IP是否正在该特定端口上进行侦听吗?

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. 您可以从命令行运行netstat -na以查看所有(包括侦听)端口。

If you add -b you will also see linked executable to each connection/listening. 如果添加-b您还将看到链接的可执行文件到每个连接/监听中。

In .NET you can get all listening connections with System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveTcpListeners() 在.NET中,您可以使用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();
       }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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