c# - 在 C# 中,如何检查 TCP 端口是否可用?

标签 c# .net tcp tcpclient

在 C# 中使用 TcpClient 或通常连接到套接字,我如何首先检查我的机器上某个端口是否空闲?

更多信息: 这是我使用的代码:

TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);

最佳答案

由于您使用的是 TcpClient,这意味着您正在检查打开的 TCP 端口。 System.Net.NetworkInformation 命名空间中有很多可用的好对象。

使用 IPGlobalProperties 对象获取一组 TcpConnectionInformation 对象,然后您可以查询端点 IP 和端口。


 int port = 456; //<--- This is your value
 bool isAvailable = true;

 // Evaluate current system tcp connections. This is the same information provided
 // by the netstat command line application, just in .Net strongly-typed object
 // form.  We will look through the list, and if our port we would like to use
 // in our TcpClient is occupied, we will set isAvailable to false.
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

 foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
 {
   if (tcpi.LocalEndPoint.Port==port)
   {
     isAvailable = false;
     break;
   }
 }

 // At this point, if isAvailable is true, we can proceed accordingly.

关于c# - 在 C# 中,如何检查 TCP 端口是否可用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/570098/

相关文章:

c# - 在 vb.net 或 c# 中寻找算法,但我不知道它的名字!

c# - 使用c#写入excel单元格

.net - 为什么 Microsoft.Extensions 记录在 ASP.NET 下

c# - 使用 C# 确定系统上 Exchange 服务器的版本

c - 为什么服务器在关闭客户端连接时进入无限循环

c# - IoC 容器 - 单例还是传递实例?

.net - "The specified procedure could not be found "禁用 wow64 重定向后

javascript - 相当于 : echo 'message' | nc -v <server> <port> 的 Node.js

android - Android 上的 TCP FAST OPEN

c# - 调用 Request.GetRawBody() 的 ServiceStack 错误;