Monday, October 12, 2009

How to check if IP port is already being used by another program?

using System.Net;
using System.Net.Sockets;
 
...
 
public static bool IsPortAvailable(Int32 port)
{
    try
    {
        using (Socket socket = 
            new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
        {
            socket.Bind(new IPEndPoint(IPAddress.Loopback, port));
            socket.Close();
        }
 
        return true;
    }
    catch (SocketException ex)
    {
        if (10048 == ex.ErrorCode)  // WSAEADDRINUSE
            return false;
 
        throw ex;
    }
}

No comments:

Post a Comment