Tobia
Tobia

Reputation: 9526

Test if a local TCP port is free

I need to test if a TCP port is free. I wrote this method:

private bool freePort(int port) {
    Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    IAsyncResult result = socket.BeginConnect(IPAddress.Loopback, port, null, null);
    bool success = result.AsyncWaitHandle.WaitOne(1000, true);
    try{
        socket.Close();
    }catch(Exception){}
    return !success;
}

This works in Windows 7 but not in Windows XP.

In winXP sometimes works and sometimes gives false answer...

Upvotes: 2

Views: 506

Answers (1)

usr
usr

Reputation: 171246

It is probably better to exactly attempt what Apache will attempt: open the port, instead of connecting to it.

using (var listener = new TcpListener(IPAddress.Loopback, port))
    listener.Start();

Upvotes: 1

Related Questions