Checking TCP Port Availability in C#
When establishing connections using TcpClient or other socket-based protocols, it is crucial to determine if a specific port is free on the local machine. Here's how it can be achieved in C#:
Since TcpClient is dedicated to managing TCP ports, the System.Net.NetworkInformation namespace provides robust tools for port availability verification.
Utilizing the IPGlobalProperties object, you can access an array of TcpConnectionInformation objects. Each entry in this array holds information about the endpoint IP and port. By iterating through this array, you can check if your desired port is occupied:
int port = 456; // Specify your port here bool isAvailable = true; // Retrieve current system TCP connections IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) { if (tcpi.LocalEndPoint.Port == port) { isAvailable = false; break; } } // Proceed with your TcpClient operations if isAvailable is true
With this approach, you can reliably verify port availability and ensure that your connections are established successfully.
The above is the detailed content of How to Check for TCP Port Availability in C#?. For more information, please follow other related articles on the PHP Chinese website!