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

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

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


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


TcpClient c;

//I want to check here if port is free.

c = new TcpClient(ip, port);


繁星点点滴滴
浏览 1024回答 3
3回答

不负相思意

由于您正在使用a&nbsp;TcpClient,这意味着您正在检查打开的TCP端口。System.Net.NetworkInformation命名空间中有许多可用的好对象。使用该IPGlobalProperties对象获取对象数组,TcpConnectionInformation然后可以查询端点IP和端口。&nbsp;int&nbsp;port&nbsp;=&nbsp;456;&nbsp;//<---&nbsp;This&nbsp;is&nbsp;your&nbsp;value &nbsp;bool&nbsp;isAvailable&nbsp;=&nbsp;true; &nbsp;//&nbsp;Evaluate&nbsp;current&nbsp;system&nbsp;tcp&nbsp;connections.&nbsp;This&nbsp;is&nbsp;the&nbsp;same&nbsp;information&nbsp;provided &nbsp;//&nbsp;by&nbsp;the&nbsp;netstat&nbsp;command&nbsp;line&nbsp;application,&nbsp;just&nbsp;in&nbsp;.Net&nbsp;strongly-typed&nbsp;object &nbsp;//&nbsp;form.&nbsp;&nbsp;We&nbsp;will&nbsp;look&nbsp;through&nbsp;the&nbsp;list,&nbsp;and&nbsp;if&nbsp;our&nbsp;port&nbsp;we&nbsp;would&nbsp;like&nbsp;to&nbsp;use &nbsp;//&nbsp;in&nbsp;our&nbsp;TcpClient&nbsp;is&nbsp;occupied,&nbsp;we&nbsp;will&nbsp;set&nbsp;isAvailable&nbsp;to&nbsp;false. &nbsp;IPGlobalProperties&nbsp;ipGlobalProperties&nbsp;=&nbsp;IPGlobalProperties.GetIPGlobalProperties(); &nbsp;TcpConnectionInformation[]&nbsp;tcpConnInfoArray&nbsp;=&nbsp;ipGlobalProperties.GetActiveTcpConnections(); &nbsp;foreach&nbsp;(TcpConnectionInformation&nbsp;tcpi&nbsp;in&nbsp;tcpConnInfoArray) &nbsp;{ &nbsp;&nbsp;&nbsp;if&nbsp;(tcpi.LocalEndPoint.Port==port) &nbsp;&nbsp;&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;isAvailable&nbsp;=&nbsp;false; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;break; &nbsp;&nbsp;&nbsp;} &nbsp;} &nbsp;//&nbsp;At&nbsp;this&nbsp;point,&nbsp;if&nbsp;isAvailable&nbsp;is&nbsp;true,&nbsp;we&nbsp;can&nbsp;proceed&nbsp;accordingly.
打开App,查看更多内容
随时随地看视频慕课网APP