开发者

c# Sure Fire Way to Detect Port Usage

Been back and forth on this recently. Trying to attach a SSH tunnel from a localhost port on my machine to an internal port on the other side of an Internet accessible SSH server using Putty. Putty does not check if the port is available. Before I open the Putty connection, I would like to verify the port is free.

It works fine if the port is available, but I need a sure fire way to guarantee the port is not open at the time I check it in my code.开发者_开发百科 I have used various methods with bad results. I am currently using the following code:

    bool IsBusy(int port)
    {
        IPGlobalProperties ipGP = IPGlobalProperties.GetIPGlobalProperties();
        IPEndPoint[] endpoints = ipGP.GetActiveTcpListeners();
        if (endpoints == null || endpoints.Length == 0) return false;
        for (int i = 0; i < endpoints.Length; i++)
            if (endpoints[i].Port == port)
                return true;
        return false;
    }

I have uTorrent installed on the computer. When I attempt to use port 3390, it fails because uTorrent is listening on that port via TCP. Is there a way to ensure TCP is not in use at all on a given port?


There will always be a race condition if you are checking with one program and expecting to use the port in another. If you were doing everything from within one program You can create a socket and bind to port 0 and the system will select a free port for you so you will never clash with another process.


All right, given that you do not care about race conditions.

Try to bind() a socket() to the port on the wildcard IP address (0.0.0.0). If this succeeds, nobody has the port. (Of course, now you have the port so don't forget to close it.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜