views:

49

answers:

1

In advance, thank you for your advice.

I am currently working on a program which uses Putty to create a SSH connection with a server that uses local port forwarding to enable a client, running my software, to access the service behind the SSH server via localhost.

IE: client:20100 -> Internet -> Remote SSH server exposed via router/firewall -> Local Intranet -> Intranet Web POP3 Server:110.

Cmd Line: "putty -ssh -2 -P 22 -C -L 20100:intranteIP:110 -pw sshpassword sshusername@sshserver"

Client would use putty to create a SSH connection with the SSH server specifying in the connection string that it would like to tie port 110 of the Intranet POP3 Server to port 20100 on the client system. Therefore the client would be able to open up a mail client to localhost:20100 and interact with the Internal POP3 server over the SSH tunnel. The above is a general description. I already know what I am trying to do will work without a problem so am not looking for debate on the above.

The question is this...How can I ensure the local port (I cannot use dynamic ports, so it must be static) on localhost is not being used or listened to by any other application?

I am currently executing this code in my C# app:

private bool checkPort(int port)
{
    try
    {
        //Create a socket on the current IPv4 address
        Socket TestSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

        // Create an IP end point
        IPEndPoint localIP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);

        // Bind that port
        TestSocket.Bind(localIP);

        // Cleanup
        TestSocket.Close();

        return false;
    }
    catch (Exception e)
    {
        // Exception occurred. Port is already bound.
        return true;
    }
}

I am currently calling this function starting with a specific port in a for loop to get the 'false' return at the first available port. The first port I try is actually being listened to by uTorrent. The above code does not catch this and my connection fails.

What is the best method to ensure a port is truly free? I do understand some other program may grab the port during/after I have tested it. I just need to find something that will ensure it is not currently in use AT ALL when the test is executed.

If there is a way to truly reserve the localhost port during the test, I would love to hear about it.

+1  A: 

Here's the answer how to check if local port is free.

I would recommend this way:

bool IsBusy(int port)
{
    IPGlobalProperties ipGP = IPGlobalProperties.GetIPGlobalProperties();
    IPEndPoint[] endpoints = ipGlobalProperties.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;          
}
Vadmyst
Excellent, thank you!
ThaKidd
Unfortunately, all three examples on that site failed to detect uTorrent listening on the starting port. That's so weird. Any other ideas?
ThaKidd
Can you show the output of command "netstat -anbp tcp". I'm interested in the lines with uTorrent.exe
Vadmyst