Thursday, January 5, 2012

How to check if a TCP port is available for listening

This sample code shows how to check if a TCP port is available for listening on the local computer.

using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
public bool TcpPortIsAvailableForListening(int port)
{
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
IPEndPoint[] tcpEndPointArray = ipGlobalProperties.GetActiveTcpListeners();
var isUnavailable = tcpEndPointArray.Any(endPoint => endPoint.Port == port);
return !isUnavailable;
}
view raw gistfile1.cs hosted with ❤ by GitHub

No comments:

Post a Comment