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

How to Check for TCP Port Availability in C#?

Barbara Streisand
Release: 2024-12-30 20:04:10
Original
249 people have browsed it

How to Check for TCP Port Availability in C#?

Checking TCP Port Availability in C#

When establishing connections using TcpClient or other socket-based protocols, it is crucial to determine if a specific port is free on the local machine. Here's how it can be achieved in C#:

Since TcpClient is dedicated to managing TCP ports, the System.Net.NetworkInformation namespace provides robust tools for port availability verification.

Utilizing the IPGlobalProperties object, you can access an array of TcpConnectionInformation objects. Each entry in this array holds information about the endpoint IP and port. By iterating through this array, you can check if your desired port is occupied:

int port = 456; // Specify your port here
bool isAvailable = true;

// Retrieve current system TCP connections
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
    if (tcpi.LocalEndPoint.Port == port)
    {
        isAvailable = false;
        break;
    }
}

// Proceed with your TcpClient operations if isAvailable is true
Copy after login

With this approach, you can reliably verify port availability and ensure that your connections are established successfully.

The above is the detailed content of How to Check for TCP Port Availability 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