Verifying TCP Port Availability in C#
When attempting to use a TcpClient or connect to a socket in C#, it's crucial to ensure that the intended port on your machine is available before proceeding. Here's how to perform this essential check:
Since TCP ports are the focus when working with TcpClient, consider utilizing the System.Net.NetworkInformation namespace. The IPGlobalProperties object provides access to an array of TcpConnectionInformation objects that reveal endpoint IP and port information.
Examine this code sample:
int port = 456; // Replace with your target port bool isAvailable = true; // Acquire system TCP connection details IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); // Inspect connections for port occupancy foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) { if (tcpi.LocalEndPoint.Port == port) { isAvailable = false; break; } } // Proceed with your connection logic only if the port is available if (isAvailable) { // Perform necessary actions }
By following these steps, you can effectively check the availability of a specific TCP port on your machine, ensuring a reliable connection establishment.
The above is the detailed content of How to Verify TCP Port Availability in C#?. For more information, please follow other related articles on the PHP Chinese website!