2

Creating a windows application to check connection to a few servers. How it is possible to check weather there is a connection exist with the specified port on remote ip?

Is there any windows in-built command to check a remote port (command line)?

Don't know weather the port is a TCP or UDP port before checking. How it is possible .

Thanks in advance

1 Answers1

2

From my (german) blog: enter link description here

Update: The tool supports UDP and multi-port-ping now too.

It'll return true, if the port is opened. This is old-fashioned code (without TPL), but it works.

var result = false;
using (var client = new TcpClient())
{
    try
    {
        client.ReceiveTimeout = timeout * 1000;
        client.SendTimeout = timeout * 1000;
        var asyncResult = client.BeginConnect(host, port, null, null);
        var waitHandle = asyncResult.AsyncWaitHandle;
        try
        {
            if (!asyncResult.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(timeout), false))
            {
                // wait handle didn't came back in time
                client.Close();
            }
            else
            {
                // The result was positiv
                result = client.Connected;
            }
            // ensure the ending-call
            client.EndConnect(asyncResult);
        }
        finally
        {
            // Ensure to close the wait handle.
            waitHandle.Close();
        }
    }
    catch
    {
    }
}
return result;
Alexander Schmidt
  • 5,631
  • 4
  • 39
  • 79