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

How to Verify TCP Port Availability in C#?

Mary-Kate Olsen
Release: 2024-12-31 07:01:10
Original
419 people have browsed it

How to Verify TCP Port Availability in C#?

Verifying TCP Port Availability in C#

When attempting to use a TcpClient or connect to a socket in C#, it's crucial to ensure that the intended port on your machine is available before proceeding. Here's how to perform this essential check:

Since TCP ports are the focus when working with TcpClient, consider utilizing the System.Net.NetworkInformation namespace. The IPGlobalProperties object provides access to an array of TcpConnectionInformation objects that reveal endpoint IP and port information.

Examine this code sample:

int port = 456; // Replace with your target port
bool isAvailable = true;

// Acquire system TCP connection details
IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

// Inspect connections for port occupancy
foreach (TcpConnectionInformation tcpi in tcpConnInfoArray)
{
  if (tcpi.LocalEndPoint.Port == port)
  {
    isAvailable = false;
    break;
  }
}

// Proceed with your connection logic only if the port is available
if (isAvailable)
{
  // Perform necessary actions
}
Copy after login

By following these steps, you can effectively check the availability of a specific TCP port on your machine, ensuring a reliable connection establishment.

The above is the detailed content of How to Verify 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