在c#中,如何检查TCP端口是否可用?

时间:2020-12-04 16:55:08

In C# to use a TcpClient or generally to connect to a socket how can I first check if a certain port is free on my machine?

在c#中,要使用TcpClient或通常连接到套接字,如何首先检查机器上的某个端口是否空闲?

more info: This is the code I use:

更多信息:这是我使用的代码:

TcpClient c;
//I want to check here if port is free.
c = new TcpClient(ip, port);

16 个解决方案

#1


195  

Since you're using a TcpClient, that means you're checking open TCP ports. There are lots of good objects available in the System.Net.NetworkInformation namespace.

由于您正在使用TcpClient,这意味着您正在检查打开的TCP端口。在System.Net中有很多好的对象。NetworkInformation名称空间。

Use the IPGlobalProperties object to get to an array of TcpConnectionInformation objects, which you can then interrogate about endpoint IP and port.

使用IPGlobalProperties对象来获取一个TcpConnectionInformation对象数组,然后您可以询问端点IP和端口。


 int port = 456; //<--- This is your value
 bool isAvailable = true;

 // Evaluate current system tcp connections. This is the same information provided
 // by the netstat command line application, just in .Net strongly-typed object
 // form.  We will look through the list, and if our port we would like to use
 // in our TcpClient is occupied, we will set isAvailable to false.
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

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

 // At this point, if isAvailable is true, we can proceed accordingly.

#2


38  

You're on the wrong end of the Intertube. It is the server that can have only one particular port open. Some code:

你走错了。服务器只能打开一个特定端口。一些代码:

  IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
  try {
    TcpListener tcpListener = new TcpListener(ipAddress, 666);
    tcpListener.Start();
  }
  catch (SocketException ex) {
    MessageBox.Show(ex.Message, "kaboom");
  }

Fails with:

失败:

Only one usage of each socket address (protocol/network address/port) is normally permitted.

通常只允许使用每个套接字地址(协议/网络地址/端口)。

#3


17  

When you set up a TCP connection, the 4-tuple (source-ip, source-port, dest-ip, dest-port) has to be unique - this is to ensure packets are delivered to the right place.

当您建立一个TCP连接时,4元组(源-ip、源-端口、源-ip、端-端口)必须是唯一的——这是为了确保数据包被传送到正确的位置。

There is a further restriction on the server side that only one server program can bind to an incoming port number (assuming one IP address; multi-NIC servers have other powers but we don't need to discuss them here).

服务器端还有一个限制,即只有一个服务器程序可以绑定到传入的端口号(假设有一个IP地址);多网卡服务器有其他功能,但我们不需要在这里讨论它们。

So, at the server end, you:

所以,在服务器端,你:

  • create a socket.
  • 创建一个套接字。
  • bind that socket to a port.
  • 将该套接字绑定到端口。
  • listen on that port.
  • 监听端口。
  • accept connections on that port. and there can be multiple connections coming in (one per client).
  • 接受该端口上的连接。而且可以有多个连接(每个客户端一个)。

On the client end, it's usually a little simpler:

在客户端,通常要简单一点:

  • create a socket.
  • 创建一个套接字。
  • open the connection. When a client opens the connection, it specifies the ip address and port of the server. It can specify its source port but usually uses zero which results in the system assigning it a free port automatically.
  • 打开连接。当客户端打开连接时,它指定服务器的ip地址和端口。它可以指定它的源端口,但通常使用0,这导致系统自动分配一个空闲端口。

There is no requirement that the destination IP/port be unique since that would result in only one person at a time being able to use Google, and that would pretty well destroy their business model.

没有要求目标IP/端口是唯一的,因为这将导致每次只能有一个人能够使用谷歌,这将很好地破坏他们的业务模型。

This means you can even do such wondrous things as multi-session FTP since you set up multiple sessions where the only difference is your source port, allowing you to download chunks in parallel. Torrents are a little different in that the destination of each session is usually different.

这意味着您甚至可以做一些奇妙的事情,比如多会话FTP,因为您设置了多个会话,其中惟一的区别是源端口,允许您并行地下载块。Torrents不同的地方,每个会话的目的地通常是不同的。

And, after all that waffling (sorry), the answer to your specific question is that you don't need to specify a free port. If you're connecting to a server with a call that doesn't specify your source port, it'll almost certainly be using zero under the covers and the system will give you an unused one.

而且,在这些胡扯之后(抱歉),您的特定问题的答案是您不需要指定一个*端口。如果您正在连接到一个没有指定源端口的服务器,它几乎肯定会在覆盖范围内使用零,系统会给您一个未使用的。

#4


14  

TcpClient c;

//I want to check here if port is free.
c = new TcpClient(ip, port);

...how can I first check if a certain port is free on my machine?

…如何首先检查机器上的某个端口是否空闲?

I mean that it is not in use by any other application. If an application is using a port others can't use it until it becomes free. – Ali

我的意思是它不被任何其他应用程序使用。如果一个应用程序使用一个端口,其他人就不能使用它,直到它变得免费为止。- - - - - -阿里

You have misunderstood what's happening here.

你误解了这里正在发生的事情。

TcpClient(...) parameters are of server ip and server port you wish to connect to.

TcpClient(…)参数是您希望连接到的服务器ip和服务器端口。

The TcpClient selects a transient local port from the available pool to communicate to the server. There's no need to check for the availability of the local port as it is automatically handled by the winsock layer.

TcpClient从可用池中选择一个临时本地端口来与服务器通信。不需要检查本地端口的可用性,因为它是由winsock层自动处理的。

In case you can't connect to the server using the above code fragment, the problem could be one or more of several. (i.e. server ip and/or port is wrong, remote server not available, etc..)

如果您无法使用上述代码片段连接到服务器,那么问题可能是多个代码片段中的一个或多个。(即服务器ip和/或端口错误,远程服务器不可用等)

#5


13  

Thanks for this tip. I needed the same functionality but on the Server side to check if a Port was in use so I modified it to this code.

谢谢你的这一建议。我需要相同的功能,但是在服务器端检查是否使用了端口,所以我将它修改为这段代码。

 private bool CheckAvailableServerPort(int port) {
    LOG.InfoFormat("Checking Port {0}", port);
    bool isAvailable = true;

    // Evaluate current system tcp connections. This is the same information provided
    // by the netstat command line application, just in .Net strongly-typed object
    // form.  We will look through the list, and if our port we would like to use
    // in our TcpClient is occupied, we will set isAvailable to false.
    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();

    foreach (IPEndPoint endpoint in tcpConnInfoArray) {
        if (endpoint.Port == port) {
            isAvailable = false;
            break;
        }
    }

    LOG.InfoFormat("Port {0} available = {1}", port, isAvailable);

    return isAvailable;
}

#6


6  

string hostname = "localhost";
int portno = 9081;
IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];


try
{
    System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
    sock.Connect(ipa, portno);
    if (sock.Connected == true)  // Port is in use and connection is successful
            MessageBox.Show("Port is Closed");
    sock.Close();

}
catch (System.Net.Sockets.SocketException ex)
{
    if (ex.ErrorCode == 10061)  // Port is unused and could not establish connection 
        MessageBox.Show("Port is Open!");
    else
        MessageBox.Show(ex.Message);
}

#7


5  

thanks for the answer jro. I had to tweak it for my usage. I needed to check if a port was being listened on, and not neccessarily active. For this I replaced

谢谢你的回答,jro。我不得不为我的使用调整它。我需要检查是否监听了一个端口,而不是必要的活动。对于这个我所取代

TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

with

IPEndPoint[] objEndPoints = ipGlobalProperties.GetActiveTcpListeners();.  

I iterated the array of endpoints checking that my port value was not found.

我迭代了端点数组,检查没有找到端口值。

#8


3  

netstat! That's a network command line utility which ships with windows. It shows all current established connections and all ports currently being listened to. You can use this program to check, but if you want to do this from code look into the System.Net.NetworkInformation namespace? It's a new namespace as of 2.0. There's some goodies there. But eventually if you wanna get the same kind of information that's available through the command netstat you'll need to result to P/Invoke...

netstat !这是一个带有windows的网络命令行实用程序。它显示所有当前建立的连接和当前正在监听的所有端口。您可以使用这个程序进行检查,但是如果您想要从代码中检查System.Net。NetworkInformation名称空间?它是2.0的一个新的命名空间。那里有一些好吃的。但是最终如果你想通过命令netstat获得同样的信息,你需要生成P/Invoke。

Update: System.Net.NetworkInformation

That namespace contains a bunch of classes you can use for figuring out things about the network.

这个名称空间包含了一些类,您可以使用它们来确定关于网络的内容。

I wasn't able to find that old pice of code but I think you can write something similar yourself. A good start is to check out the IP Helper API. Google MSDN for the GetTcpTable WINAPI function and use P/Invoke to enumerate until you have the information you need.

我找不到那些旧的代码,但我认为你可以自己写一些类似的东西。一个好的开始是检查IP Helper API。谷歌MSDN用于GetTcpTable WINAPI函数,并使用P/Invoke枚举,直到获得所需的信息。

#9


2  

You say

你说

I mean that it is not in use by any other application. If an application is using a port others can't use it until it becomes free.

我的意思是它不被任何其他应用程序使用。如果一个应用程序使用一个端口,其他人就不能使用它,直到它变得免费为止。

But you can always connect to a port while others are using it if something's listening there. Otherwise, http port 80 would be a mess.

但是,当其他人在使用端口时,如果有什么东西正在监听,您总是可以连接到该端口。否则,http端口80就会一团糟。

If your

如果你的

   c = new TcpClient(ip, port);

fails, then nothing's listening there. Otherwise, it will connect, even if some other machine/application has a socket open to that ip and port.

失败了,就没有人在听了。否则,它将连接,即使其他一些机器/应用程序有一个对该ip和端口开放的套接字。

#10


2  

If I'm not very much mistaken, you can use System.Network.whatever to check.

如果我没弄错的话,你可以用System.Network。任何检查。

However, this will always incur a race condition.

然而,这总是会导致竞态条件。

The canonical way of checking is try to listen on that port. If you get an error that port wasn't open.

检查的标准方法是尝试监听那个端口。如果你有一个错误,端口没有打开。

I think this is part of why bind() and listen() are two separate system calls.

我认为这就是为什么bind()和listen()是两个独立的系统调用。

#11


2  

ipGlobalProperties.GetActiveTcpConnections() doesn't return connections in Listen State.

getactivetcpconnections()在侦听状态下不返回连接。

Port can be used for listening, but with no one connected to it the method described above will not work.

端口可以用于监听,但是没有人连接到它,上面描述的方法将不起作用。

#12


1  

Be aware the time window between you make check and the moment you try to make connection some process may take the port - classical TOCTOU. Why don't you just try to connect? If it fails then you know the port is not available.

注意你检查的时间窗口和你尝试连接的时刻之间的时间窗口,一些过程可能采取端口-古典的TOCTOU。你为什么不试着联系一下呢?如果失败,那么您就知道端口不可用。

#13


1  

You don't have to know what ports are open on your local machine to connect to some remote TCP service (unless you want to use a specific local port, but usually that is not the case).

您不需要知道本地机器上打开哪些端口以连接到一些远程TCP服务(除非您想使用特定的本地端口,但通常情况并非如此)。

Every TCP/IP connection is identified by 4 values: remote IP, remote port number, local IP, local port number, but you only need to know remote IP and remote port number to establish a connection.

每个TCP/IP连接由4个值标识:远程IP、远程端口号、本地IP、本地端口号,但是您只需要知道远程IP和远程端口号就可以建立连接。

When you create tcp connection using

当您使用tcp创建连接时

TcpClient c;
c = new TcpClient(remote_ip, remote_port);

Your system will automatically assign one of many free local port numbers to your connection. You don't need to do anything. You might also want to check if a remote port is open. but there is no better way to do that than just trying to connect to it.

您的系统将自动为您的连接分配许多免费本地端口号之一。你什么都不需要做。您可能还想检查远程端口是否打开。但是没有更好的方法可以做到这一点。

#14


1  

    public static bool TestOpenPort(int Port)
    {
        var tcpListener = default(TcpListener);

        try
        {
            var ipAddress = Dns.GetHostEntry("localhost").AddressList[0];

            tcpListener = new TcpListener(ipAddress, Port);
            tcpListener.Start();

            return true;
        }
        catch (SocketException)
        {
        }
        finally
        {
            if (tcpListener != null)
                tcpListener.Stop();
        }

        return false;
    }

#15


0  

test_connection("ip", port);


public void test_connection(String hostname, int portno) {
  IPAddress ipa = (IPAddress)Dns.GetHostAddresses(hostname)[0];
  try {
    System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
   sock.Connect(ipa, portno);
   if (sock.Connected == true) {
     MessageBox.Show("Port is in use");
   }

   sock.Close();
 }
 catch (System.Net.Sockets.SocketException ex) {
   if (ex.ErrorCode == 10060) {
     MessageBox.Show("No connection.");
   }
 }
}

#16


-1  

try this, in my case the port number for the created object wasn't available so I came up with this

试试这个,在我的例子中,创建对象的端口号不可用,所以我想到了这个

IPEndPoint endPoint;
int port = 1;
while (true)
{
    try
    {
        endPoint = new IPEndPoint(IPAddress.Any, port);
        break;
    }
    catch (SocketException)
    {
         port++;
    }
}

#1


195  

Since you're using a TcpClient, that means you're checking open TCP ports. There are lots of good objects available in the System.Net.NetworkInformation namespace.

由于您正在使用TcpClient,这意味着您正在检查打开的TCP端口。在System.Net中有很多好的对象。NetworkInformation名称空间。

Use the IPGlobalProperties object to get to an array of TcpConnectionInformation objects, which you can then interrogate about endpoint IP and port.

使用IPGlobalProperties对象来获取一个TcpConnectionInformation对象数组,然后您可以询问端点IP和端口。


 int port = 456; //<--- This is your value
 bool isAvailable = true;

 // Evaluate current system tcp connections. This is the same information provided
 // by the netstat command line application, just in .Net strongly-typed object
 // form.  We will look through the list, and if our port we would like to use
 // in our TcpClient is occupied, we will set isAvailable to false.
 IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
 TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

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

 // At this point, if isAvailable is true, we can proceed accordingly.

#2


38  

You're on the wrong end of the Intertube. It is the server that can have only one particular port open. Some code:

你走错了。服务器只能打开一个特定端口。一些代码:

  IPAddress ipAddress = Dns.GetHostEntry("localhost").AddressList[0];
  try {
    TcpListener tcpListener = new TcpListener(ipAddress, 666);
    tcpListener.Start();
  }
  catch (SocketException ex) {
    MessageBox.Show(ex.Message, "kaboom");
  }

Fails with:

失败:

Only one usage of each socket address (protocol/network address/port) is normally permitted.

通常只允许使用每个套接字地址(协议/网络地址/端口)。

#3


17  

When you set up a TCP connection, the 4-tuple (source-ip, source-port, dest-ip, dest-port) has to be unique - this is to ensure packets are delivered to the right place.

当您建立一个TCP连接时,4元组(源-ip、源-端口、源-ip、端-端口)必须是唯一的——这是为了确保数据包被传送到正确的位置。

There is a further restriction on the server side that only one server program can bind to an incoming port number (assuming one IP address; multi-NIC servers have other powers but we don't need to discuss them here).

服务器端还有一个限制,即只有一个服务器程序可以绑定到传入的端口号(假设有一个IP地址);多网卡服务器有其他功能,但我们不需要在这里讨论它们。

So, at the server end, you:

所以,在服务器端,你:

  • create a socket.
  • 创建一个套接字。
  • bind that socket to a port.
  • 将该套接字绑定到端口。
  • listen on that port.
  • 监听端口。
  • accept connections on that port. and there can be multiple connections coming in (one per client).
  • 接受该端口上的连接。而且可以有多个连接(每个客户端一个)。

On the client end, it's usually a little simpler:

在客户端,通常要简单一点:

  • create a socket.
  • 创建一个套接字。
  • open the connection. When a client opens the connection, it specifies the ip address and port of the server. It can specify its source port but usually uses zero which results in the system assigning it a free port automatically.
  • 打开连接。当客户端打开连接时,它指定服务器的ip地址和端口。它可以指定它的源端口,但通常使用0,这导致系统自动分配一个空闲端口。

There is no requirement that the destination IP/port be unique since that would result in only one person at a time being able to use Google, and that would pretty well destroy their business model.

没有要求目标IP/端口是唯一的,因为这将导致每次只能有一个人能够使用谷歌,这将很好地破坏他们的业务模型。

This means you can even do such wondrous things as multi-session FTP since you set up multiple sessions where the only difference is your source port, allowing you to download chunks in parallel. Torrents are a little different in that the destination of each session is usually different.

这意味着您甚至可以做一些奇妙的事情,比如多会话FTP,因为您设置了多个会话,其中惟一的区别是源端口,允许您并行地下载块。Torrents不同的地方,每个会话的目的地通常是不同的。

And, after all that waffling (sorry), the answer to your specific question is that you don't need to specify a free port. If you're connecting to a server with a call that doesn't specify your source port, it'll almost certainly be using zero under the covers and the system will give you an unused one.

而且,在这些胡扯之后(抱歉),您的特定问题的答案是您不需要指定一个*端口。如果您正在连接到一个没有指定源端口的服务器,它几乎肯定会在覆盖范围内使用零,系统会给您一个未使用的。

#4


14  

TcpClient c;

//I want to check here if port is free.
c = new TcpClient(ip, port);

...how can I first check if a certain port is free on my machine?

…如何首先检查机器上的某个端口是否空闲?

I mean that it is not in use by any other application. If an application is using a port others can't use it until it becomes free. – Ali

我的意思是它不被任何其他应用程序使用。如果一个应用程序使用一个端口,其他人就不能使用它,直到它变得免费为止。- - - - - -阿里

You have misunderstood what's happening here.

你误解了这里正在发生的事情。

TcpClient(...) parameters are of server ip and server port you wish to connect to.

TcpClient(…)参数是您希望连接到的服务器ip和服务器端口。

The TcpClient selects a transient local port from the available pool to communicate to the server. There's no need to check for the availability of the local port as it is automatically handled by the winsock layer.

TcpClient从可用池中选择一个临时本地端口来与服务器通信。不需要检查本地端口的可用性,因为它是由winsock层自动处理的。

In case you can't connect to the server using the above code fragment, the problem could be one or more of several. (i.e. server ip and/or port is wrong, remote server not available, etc..)

如果您无法使用上述代码片段连接到服务器,那么问题可能是多个代码片段中的一个或多个。(即服务器ip和/或端口错误,远程服务器不可用等)

#5


13  

Thanks for this tip. I needed the same functionality but on the Server side to check if a Port was in use so I modified it to this code.

谢谢你的这一建议。我需要相同的功能,但是在服务器端检查是否使用了端口,所以我将它修改为这段代码。

 private bool CheckAvailableServerPort(int port) {
    LOG.InfoFormat("Checking Port {0}", port);
    bool isAvailable = true;

    // Evaluate current system tcp connections. This is the same information provided
    // by the netstat command line application, just in .Net strongly-typed object
    // form.  We will look through the list, and if our port we would like to use
    // in our TcpClient is occupied, we will set isAvailable to false.
    IPGlobalProperties ipGlobalProperties = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpListeners();

    foreach (IPEndPoint endpoint in tcpConnInfoArray) {
        if (endpoint.Port == port) {
            isAvailable = false;
            break;
        }
    }

    LOG.InfoFormat("Port {0} available = {1}", port, isAvailable);

    return isAvailable;
}

#6


6  

string hostname = "localhost";
int portno = 9081;
IPAddress ipa = (IPAddress) Dns.GetHostAddresses(hostname)[0];


try
{
    System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
    sock.Connect(ipa, portno);
    if (sock.Connected == true)  // Port is in use and connection is successful
            MessageBox.Show("Port is Closed");
    sock.Close();

}
catch (System.Net.Sockets.SocketException ex)
{
    if (ex.ErrorCode == 10061)  // Port is unused and could not establish connection 
        MessageBox.Show("Port is Open!");
    else
        MessageBox.Show(ex.Message);
}

#7


5  

thanks for the answer jro. I had to tweak it for my usage. I needed to check if a port was being listened on, and not neccessarily active. For this I replaced

谢谢你的回答,jro。我不得不为我的使用调整它。我需要检查是否监听了一个端口,而不是必要的活动。对于这个我所取代

TcpConnectionInformation[] tcpConnInfoArray = ipGlobalProperties.GetActiveTcpConnections();

with

IPEndPoint[] objEndPoints = ipGlobalProperties.GetActiveTcpListeners();.  

I iterated the array of endpoints checking that my port value was not found.

我迭代了端点数组,检查没有找到端口值。

#8


3  

netstat! That's a network command line utility which ships with windows. It shows all current established connections and all ports currently being listened to. You can use this program to check, but if you want to do this from code look into the System.Net.NetworkInformation namespace? It's a new namespace as of 2.0. There's some goodies there. But eventually if you wanna get the same kind of information that's available through the command netstat you'll need to result to P/Invoke...

netstat !这是一个带有windows的网络命令行实用程序。它显示所有当前建立的连接和当前正在监听的所有端口。您可以使用这个程序进行检查,但是如果您想要从代码中检查System.Net。NetworkInformation名称空间?它是2.0的一个新的命名空间。那里有一些好吃的。但是最终如果你想通过命令netstat获得同样的信息,你需要生成P/Invoke。

Update: System.Net.NetworkInformation

That namespace contains a bunch of classes you can use for figuring out things about the network.

这个名称空间包含了一些类,您可以使用它们来确定关于网络的内容。

I wasn't able to find that old pice of code but I think you can write something similar yourself. A good start is to check out the IP Helper API. Google MSDN for the GetTcpTable WINAPI function and use P/Invoke to enumerate until you have the information you need.

我找不到那些旧的代码,但我认为你可以自己写一些类似的东西。一个好的开始是检查IP Helper API。谷歌MSDN用于GetTcpTable WINAPI函数,并使用P/Invoke枚举,直到获得所需的信息。

#9


2  

You say

你说

I mean that it is not in use by any other application. If an application is using a port others can't use it until it becomes free.

我的意思是它不被任何其他应用程序使用。如果一个应用程序使用一个端口,其他人就不能使用它,直到它变得免费为止。

But you can always connect to a port while others are using it if something's listening there. Otherwise, http port 80 would be a mess.

但是,当其他人在使用端口时,如果有什么东西正在监听,您总是可以连接到该端口。否则,http端口80就会一团糟。

If your

如果你的

   c = new TcpClient(ip, port);

fails, then nothing's listening there. Otherwise, it will connect, even if some other machine/application has a socket open to that ip and port.

失败了,就没有人在听了。否则,它将连接,即使其他一些机器/应用程序有一个对该ip和端口开放的套接字。

#10


2  

If I'm not very much mistaken, you can use System.Network.whatever to check.

如果我没弄错的话,你可以用System.Network。任何检查。

However, this will always incur a race condition.

然而,这总是会导致竞态条件。

The canonical way of checking is try to listen on that port. If you get an error that port wasn't open.

检查的标准方法是尝试监听那个端口。如果你有一个错误,端口没有打开。

I think this is part of why bind() and listen() are two separate system calls.

我认为这就是为什么bind()和listen()是两个独立的系统调用。

#11


2  

ipGlobalProperties.GetActiveTcpConnections() doesn't return connections in Listen State.

getactivetcpconnections()在侦听状态下不返回连接。

Port can be used for listening, but with no one connected to it the method described above will not work.

端口可以用于监听,但是没有人连接到它,上面描述的方法将不起作用。

#12


1  

Be aware the time window between you make check and the moment you try to make connection some process may take the port - classical TOCTOU. Why don't you just try to connect? If it fails then you know the port is not available.

注意你检查的时间窗口和你尝试连接的时刻之间的时间窗口,一些过程可能采取端口-古典的TOCTOU。你为什么不试着联系一下呢?如果失败,那么您就知道端口不可用。

#13


1  

You don't have to know what ports are open on your local machine to connect to some remote TCP service (unless you want to use a specific local port, but usually that is not the case).

您不需要知道本地机器上打开哪些端口以连接到一些远程TCP服务(除非您想使用特定的本地端口,但通常情况并非如此)。

Every TCP/IP connection is identified by 4 values: remote IP, remote port number, local IP, local port number, but you only need to know remote IP and remote port number to establish a connection.

每个TCP/IP连接由4个值标识:远程IP、远程端口号、本地IP、本地端口号,但是您只需要知道远程IP和远程端口号就可以建立连接。

When you create tcp connection using

当您使用tcp创建连接时

TcpClient c;
c = new TcpClient(remote_ip, remote_port);

Your system will automatically assign one of many free local port numbers to your connection. You don't need to do anything. You might also want to check if a remote port is open. but there is no better way to do that than just trying to connect to it.

您的系统将自动为您的连接分配许多免费本地端口号之一。你什么都不需要做。您可能还想检查远程端口是否打开。但是没有更好的方法可以做到这一点。

#14


1  

    public static bool TestOpenPort(int Port)
    {
        var tcpListener = default(TcpListener);

        try
        {
            var ipAddress = Dns.GetHostEntry("localhost").AddressList[0];

            tcpListener = new TcpListener(ipAddress, Port);
            tcpListener.Start();

            return true;
        }
        catch (SocketException)
        {
        }
        finally
        {
            if (tcpListener != null)
                tcpListener.Stop();
        }

        return false;
    }

#15


0  

test_connection("ip", port);


public void test_connection(String hostname, int portno) {
  IPAddress ipa = (IPAddress)Dns.GetHostAddresses(hostname)[0];
  try {
    System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
   sock.Connect(ipa, portno);
   if (sock.Connected == true) {
     MessageBox.Show("Port is in use");
   }

   sock.Close();
 }
 catch (System.Net.Sockets.SocketException ex) {
   if (ex.ErrorCode == 10060) {
     MessageBox.Show("No connection.");
   }
 }
}

#16


-1  

try this, in my case the port number for the created object wasn't available so I came up with this

试试这个,在我的例子中,创建对象的端口号不可用,所以我想到了这个

IPEndPoint endPoint;
int port = 1;
while (true)
{
    try
    {
        endPoint = new IPEndPoint(IPAddress.Any, port);
        break;
    }
    catch (SocketException)
    {
         port++;
    }
}