Wednesday, December 24, 2014

Check if port is open or not using C#

Description:
System.Net.Sockets.Socket class can be used for Socket Programming. Same class can be used to check if a particular port is open on a particular machine or not. Following code can check this:

static bool TestForOpenPort(string host, int port)
{
    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
    try
    {
        s.Connect(host, port);
        return true;
    }
    catch (SocketException)
    {
        return false;
    }
    finally
    {
        ((IDisposable)s).Dispose();
    }
}


Here host is Machine Name or IP Address.

No comments:

Post a Comment