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

How Can I Check for TCP Port Availability in C#?

Mary-Kate Olsen
Release: 2024-12-31 03:01:08
Original
538 people have browsed it

How Can I Check for TCP Port Availability in C#?

Determining TCP Port Availability in C#: A Comprehensive Guide

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.

Leveraging IPGlobalProperties

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.

Sample Code: Checking Port Availability

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

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!

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