Home > Backend Development > C++ > Is a TCP Port Available in C#?

Is a TCP Port Available in C#?

Barbara Streisand
Release: 2024-12-31 08:27:10
Original
905 people have browsed it

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.
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template