C# 检测本地主机端口使用情况 [英] C# Detect Localhost Port Usage

查看:93
本文介绍了C# 检测本地主机端口使用情况的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

提前感谢您的建议.

我目前正在开发一个程序,该程序使用 Putty 创建与服务器的 SSH 连接,该服务器使用本地端口转发使运行我的软件的客户端能够通过本地主机访问 SSH 服务器后面的服务.

I am currently working on a program which uses Putty to create a SSH connection with a server that uses local port forwarding to enable a client, running my software, to access the service behind the SSH server via localhost.

IE: client:20100 -> Internet -> 通过路由器/防火墙暴露的远程 SSH 服务器 -> 本地 Intranet -> Intranet Web POP3 Server:110.

IE: client:20100 -> Internet -> Remote SSH server exposed via router/firewall -> Local Intranet -> Intranet Web POP3 Server:110.

命令行:putty -ssh -2 -P 22 -C -L 20100:inranteIP:110 -pw sshpassword sshusername@sshserver"

Cmd Line: "putty -ssh -2 -P 22 -C -L 20100:intranteIP:110 -pw sshpassword sshusername@sshserver"

客户端将使用 putty 创建与 SSH 服务器的 SSH 连接,并在连接字符串中指定它要将 Intranet POP3 服务器的端口 110 绑定到客户端系统上的端口 20100.因此,客户端将能够打开一个到 localhost:20100 的邮件客户端,并通过 SSH 隧道与内部 POP3 服务器交互.以上是一般的描述.我已经知道我正在尝试做的事情不会有问题,所以我不想就上述内容进行辩论.

Client would use putty to create a SSH connection with the SSH server specifying in the connection string that it would like to tie port 110 of the Intranet POP3 Server to port 20100 on the client system. Therefore the client would be able to open up a mail client to localhost:20100 and interact with the Internal POP3 server over the SSH tunnel. The above is a general description. I already know what I am trying to do will work without a problem so am not looking for debate on the above.

问题是……我怎样才能确保本地主机上的本地端口(我不能使用动态端口,所以它必须是静态的)没有被任何其他应用程序使用或监听?

The question is this...How can I ensure the local port (I cannot use dynamic ports, so it must be static) on localhost is not being used or listened to by any other application?

我目前正在我的 C# 应用程序中执行此代码:

I am currently executing this code in my C# app:

private bool checkPort(int port)
{
    try
    {
        //Create a socket on the current IPv4 address
        Socket TestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // Create an IP end point
        IPEndPoint localIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

        // Bind that port
        TestSocket.Bind(localIP);

        // Cleanup
        TestSocket.Close();

        return false;
    }
    catch (Exception e)
    {
        // Exception occurred. Port is already bound.
        return true;
    }
}

我目前正在以 for 循环中的特定端口开始调用此函数,以在第一个可用端口处返回false".我尝试的第一个端口实际上是被 uTorrent 监听的.上面的代码没有捕捉到这一点,我的连接失败了.

I am currently calling this function starting with a specific port in a for loop to get the 'false' return at the first available port. The first port I try is actually being listened to by uTorrent. The above code does not catch this and my connection fails.

确保端口真正免费的最佳方法是什么?我确实了解其他一些程序可能会在我测试期间/之后获取端口.我只需要找到一些可以确保在执行测试时当前根本没有使用它的东西.

What is the best method to ensure a port is truly free? I do understand some other program may grab the port during/after I have tested it. I just need to find something that will ensure it is not currently in use AT ALL when the test is executed.

如果有一种方法可以在测试期间真正保留本地主机端口,我很乐意听到.

If there is a way to truly reserve the localhost port during the test, I would love to hear about it.

推荐答案

这里是如何检查本地端口是否空闲的答案.

Here's the answer how to check if local port is free.

我会推荐这种方式:

bool IsBusy(int port)
{
    IPGlobalProperties ipGP = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] endpoints = ipGP.GetActiveTcpListeners();
    if ( endpoints == null || endpoints.Length == 0 ) return false;
    for(int i = 0; i < endpoints.Length; i++)
        if ( endpoints[i].Port == port )
            return true;
    return false;          
}

这篇关于C# 检测本地主机端口使用情况的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆