c# - 测试本地 TCP 端口是否空闲

标签 c# .net-4.0 tcp

我需要测试 TCP 端口是否空闲。我写了这个方法:

private bool freePort(int port) {
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IAsyncResult result = socket.BeginConnect(IPAddress.Loopback, port, null, null);
    bool success = result.AsyncWaitHandle.WaitOne(1000, true);
    try{
        socket.Close();
    }catch(Exception){}
    return !success;
}

这适用于 Windows 7,但不适用于 Windows XP。

在 winXP 中有时有效,有时给出错误答案...

最佳答案

最好完全尝试 Apache 将尝试的操作:打开端口,而不是连接到它。

using (var listener = new TcpListener(IPAddress.Loopback, port))
    listener.Start();

关于c# - 测试本地 TCP 端口是否空闲,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19024355/

相关文章:

python - TCP Receive in Python,读取数据

c# - 如何从后台线程正确更新数据绑定(bind) datagridview

c# - 如何找到实现接口(interface)的类

c# - 在存储库中使用 Include() 方法

wcf - 什么 130 秒超时正在杀死我的 WCF 流服务调用?

c# - 排序字典和列表 <>() 在 VS 2010 中有错误

java - 同一端口上的多个 TCP 服务器

tcp - 端口和 IP 地址 - 绑定(bind)是什么意思?

c# - 成员名称长度

c# - 实际上什么是Nothing——它是如何转换的