Home >Backend Development >C++ >How to Check TCP Port Availability in C#?
When establishing a connection using TcpClient or any socket, it's beneficial to verify the availability of the desired port on your machine. Here's how you can approach this:
To check the availability of a TCP port in C#, you can utilize the IPGlobalProperties object and its GetActiveTcpConnections() method within the System.Net.NetworkInformation namespace. This approach provides a robust way to assess the current TCP connections on your system.
The following code demonstrates how you can implement this check:
int port = 456; // Replace with the port you want to check bool isAvailable = true; // Get the current TCP connections IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); // Check if the specified port is already in use foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) { if (tcpi.LocalEndPoint.Port == port) { isAvailable = false; break; } } // Proceed further if the port is available if (isAvailable) { // Your code for utilizing the port }
The above is the detailed content of How to Check TCP Port Availability in C#?. For more information, please follow other related articles on the PHP Chinese website!