C# 确定端口是否在使用中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/679489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 13:10:00  来源:igfitidea点击:

Determine if port is in use?

c#wcf

提问by Joel Martinez

Is there a way, using C#, to determine if a port is available? I'd like to check before I start up a WCF ServiceHost instance using a port that's already used :-)

有没有办法使用 C# 来确定端口是否可用?我想在使用已使用的端口启动 WCF ServiceHost 实例之前进行检查:-)

回答by JaredPar

You cannot determine if a port is available. You can only determine

您无法确定端口是否可用。你只能确定

  1. That you have control of a port
  2. That a port was available at some point in the past
  1. 你可以控制一个端口
  2. 端口在过去的某个时间可用

Unless you control the port by having a particular socket bound and listening on the port, it's possible for another process to come along and take control of the port.

除非您通过绑定特定套接字并侦听端口来控制端口,否则另一个进程可能会出现并控制端口。

The only reliable way to know if a port is available is to attempt to listen on it. If you succeed then the port is available and you have control. Otherwise you know that at some point in the pastand potentially the present, the port was controlled by another entity.

知道端口是否可用的唯一可靠方法是尝试侦听它。如果您成功,则该端口可用并且您拥有控制权。否则,您会知道在过去和现在的某个时间点,该端口由另一个实体控制。

回答by Andreas Reiff

As for In C#, how to check if a TCP port is available?, I think the original poster is not really sure if he is talking about client or server, so also the answers are either about client wanting to connect or server wanting to listen on a port.

至于在 C# 中,如何检查 TCP 端口是否可用?,我认为原始海报并不确定他是在谈论客户端还是服务器,因此答案也是关于客户端想要连接或服务器想要监听端口。

JaredPar's answer is correct (more than this one!) though sometimes maybe inconvenient.

JaredPar 的回答是正确的(不仅仅是这个!),尽管有时可能不方便。

If you are reasonably certain that no other server is grabbing the port you just checked (or don't care for occasional failure), you can try (from http://www.codeproject.com/Tips/268108/Find-the-open-port-on-a-machine-using-Csharp?msg=4176410#xx4176410xx, similar to https://stackoverflow.com/a/570461/586754):

如果您有理由确定没有其他服务器正在占用您刚刚检查的端口(或者不关心偶尔的故障),您可以尝试(来自http://www.codeproject.com/Tips/268108/Find-the- open-port-on-a-machine-using-Csharp?msg=4176410#xx4176410xx,类似于https://stackoverflow.com/a/570461/586754):

public static int GetOpenPort(int startPort = 2555)
{
    int portStartIndex = startPort;
    int count = 99;
    IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] tcpEndPoints = properties.GetActiveTcpListeners();

    List<int> usedPorts = tcpEndPoints.Select(p => p.Port).ToList<int>();
    int unusedPort = 0;

    unusedPort = Enumerable.Range(portStartIndex, 99).Where(port => !usedPorts.Contains(port)).FirstOrDefault();
    return unusedPort;
}