本文介绍了在 C# 中,如何检查 TCP 端口是否可用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In C# to use a TcpClient or generally to connect to a socket how can I first check if a certain port is free on my machine?

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

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

推荐答案

由于您使用的是 TcpClient,这意味着您正在检查打开的 TCP 端口.System.Net.NetworkInformation 命名空间.

Since you're using a TcpClient, that means you're checking open TCP ports. There are lots of good objects available in the System.Net.NetworkInformation namespace.

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

Use the IPGlobalProperties object to get to an array of TcpConnectionInformation objects, which you can then interrogate about endpoint IP and port.

 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# 中,如何检查 TCP 端口是否可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!