C# Detect Localhost Port Usage

Posted by ThaKidd on Stack Overflow See other posts from Stack Overflow or by ThaKidd
Published on 2010-06-17T06:04:06Z Indexed on 2010/06/17 6:13 UTC
Read the original article Hit count: 277

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.

© Stack Overflow or respective owner

Related posts about networking

Related posts about network-programming