views:

51

answers:

2

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?

+3  A: 

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.

Gary
I am not expecting an end all be all...I realize a port may be taken between test and use. My only concern with this app is to ensure that the port I test is really available at the time of the test..no questions asked. The above code fails...hence the question. I just want to test the port and if it is available, point Putty to grab it.
ThaKidd
+1  A: 

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.)

Joshua
Okay. I will give that a shot this weekend and post back.
ThaKidd