gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:38:52 27 4
gpt4 key购买 nike

创建一个 Windows 应用程序来检查与一些服务器的连接。如何检查是否存在与远程 ip 上指定端口的连接?

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

在检查之前不知道端口是 TCP 还是 UDP 端口。怎么可能。

提前致谢

最佳答案

来 self 的(德语)博客: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;

关于c# - 如何检查远程端口是否打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26277390/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com