在C#中,如何检查TCP端口可用? [英] In C#, how to check if a TCP port is available?

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

问题描述

在C#中使用TcpClient的或一般连接到插座如何我第一次检查,如果某个端口是免费在我的机器上?

详细信息:的 这是code我用:

 的TcpClient℃;
//我要检查这里如果端口是免费的。
C =新的TcpClient(IP,端口);
 

由于您使用的是的TcpClient 解决方案

,这意味着你检查开放TCP端口。有很多不错的对象,在<一个可用href="http://msdn.microsoft.com/en-us/library/system.net.networkinformation.aspx">System.Net.NetworkInformation命名空间。

使用了 IPGlobalProperties 目标去的 TcpConnectionInformation 的对象,然后您可以询问有关端点IP阵列和端口。


  INT端口= 456; //&LT; ---这是你的价值
 布尔isAvailable = TRUE;

 //评估当前的系统的TCP连接。这是所提供的相同的信息
 //通过netstat命令行应用程序,只需在净强类型的对象
 // 形成。我们将看看在列表中,如果我们的港口,我们想用
 //我们TcpClient的被占用,我们将设置isAvailable为false。
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation [] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

 的foreach(在tcpConnInfoArray TcpConnectionInformation TCPI)
 {
   如果(tcpi.LocalEndPoint.Port ==口)
   {
     isAvailable = FALSE;
     打破;
   }
 }

 //此时,如果isAvailable是真的,我们可以照此办理。
 

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?

more info: This is the code I use:

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

解决方案

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.

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端口可用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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