Home >Backend Development >C++ >Is a TCP Port Available in C#?
How to Determine TCP Port Availability in C#
If you wish to utilize a TcpClient or establish a connection to a socket in C#, it's essential to verify the availability of a specific port on your system beforehand.
To check if a port is open, you can utilize objects within the System.Net.NetworkInformation namespace.
Obtain the IPGlobalProperties object, which provides access to an array of TcpConnectionInformation objects. These objects contain information about endpoint IP and port. By scrutinizing this collection, you can identify if the desired port for your TcpClient is currently occupied.
Here's an example code snippet:
int port = 456; // Substitute with your desired port number bool isAvailable = true; // Assess active TCP connections on the system IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties(); TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections(); foreach (TcpConnectionInformation tcpi in tcpConnInfoArray) { if (tcpi.LocalEndPoint.Port == port) { isAvailable = false; break; } } // If isAvailable remains true after this loop, the port is free to use.
The above is the detailed content of Is a TCP Port Available in C#?. For more information, please follow other related articles on the PHP Chinese website!