在C#中,要使用TcpClient或一般情况下连接到套接字,我如何首先判断机器上的某个端口是否空闲?

more info:个 这是我使用的代码:

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.

.net相关问答推荐

AppShell - 返回导航失败,匹配的路由不明确......但我只注册了一次路由

F#:跨度、提升和底部类型(或缺乏)

在 Git for Visual Studio 2012 中恢复到以前的提交

如何将 Javascript 日期时间转换为 C# 日期时间?

Owin Twitter登录-根据验证程序远程证书无效

从 switch 块中跳出 foreach 循环

数据库架构更改后更新 LINQ to SQL 类的最佳方法

从 .NET 中的字符串末尾修剪字符串 - 为什么会丢失?

我不了解应用程序域

是否有可用的 WPF 备忘单?

析构函数、dispose 和 finalize 方法的区别

在 C#/.NET 中组合路径和文件名的最佳方法是什么?

Dispatcher.CurrentDispatcher 与 Application.Current.Dispatcher

String.Join 与 StringBuilder:哪个更快?

为什么 double.NaN 不等于自身?

使用 DateTime.ToString() 时获取日期后缀

System.Array.CopyTo() 和 System.Array.Clone() 之间的区别

程序员应该使用 SSIS,如果是,为什么?

多个列表与 IEnumerable.Intersect() 的交集

.NET 桌面应用程序中的 Settings.settings 与 app.config