When utilizing a TcpClient in C#, determining the availability of a specific port on your machine is crucial. This guide explores the most effective method to perform this check.
To ensure your TcpClient connects to an open socket, you'll need to verify its port status. The System.Net.NetworkInformation namespace houses a collection of valuable objects for this purpose.
The IPGlobalProperties object grants access to an array of TcpConnectionInformation objects. These objects hold essential data regarding endpoint IP addresses and ports. By examining these objects, you can establish whether your desired port is occupied.
Consider the following code snippet:
int port = 456; // Substitute with your port value bool isAvailable = true; // Retrieve network information IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); // Examine all active TCP connections TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) { if (tcpi.LocalEndPoint.Port == port) { isAvailable = false; break; } } // Logic based on isAvailable status if (isAvailable) { // Proceed with TcpClient creation }
By executing this code, you'll determine whether the specified TCP port is available for use. If it is not occupied, you can proceed with confidence.
The above is the detailed content of How Can I Check for TCP Port Availability in C#?. For more information, please follow other related articles on the PHP Chinese website!