如何检查远程端口是否打开

时间:2014-10-09 11:35:25

标签: c# winforms sockets command-line-arguments

创建Windows应用程序以检查与几台服务器的连接。如何检查天气是否存在远程ip上指定端口的连接?

是否有任何Windows内置命令来检查远程端口(命令行)?

在检查之前,不知道端口是TCP或UDP端口的天气。怎么可能。

提前致谢

1 个答案:

答案 0 :(得分:1)

来自我的(德国)博客:enter link description here

更新:该工具现在也支持UDP和多端口ping。

如果打开端口,它将返回true。这是老式代码(没有TPL),但它有效。

var result = false;
using (var client = new TcpClient())
{
    try
    {
        client.ReceiveTimeout = timeout * 1000;
        client.SendTimeout = timeout * 1000;
        var asyncResult = client.BeginConnect(host, port, null, null);
        var waitHandle = asyncResult.AsyncWaitHandle;
        try
        {
            if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
            {
                // wait handle didn't came back in time
                client.Close();
            }
            else
            {
                // The result was positiv
                result = client.Connected;
            }
            // ensure the ending-call
            client.EndConnect(asyncResult);
        }
        finally
        {
            // Ensure to close the wait handle.
            waitHandle.Close();
        }
    }
    catch
    {
    }
}
return result;
相关问题