Home >Backend Development >C++ >How to Check TCP Port Availability in C#?

How to Check TCP Port Availability in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-03 10:34:40550browse

How to Check TCP Port Availability in C#?

How can you check if a TCP port is available 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn