AxelS
AxelS

Reputation: 329

Check whether a server is online using an IP and Port

I have two inputBoxes, IP/Address and Port.

I search a simple code that can check if server (address + port) is online or offline. The result will displayed in e.g. a label (Online/Offline).

The server check can be with a timer or button.

Upvotes: 3

Views: 28681

Answers (2)

Olaru Mircea
Olaru Mircea

Reputation: 2620

TcpClient tcpClient = new TcpClient();
try
{
    tcpClient.Connect("192.168.0.1", 22);
    Console.WriteLine("Port open");
}
catch (Exception)
{
    Console.WriteLine("Port closed");
}

This snippet will work for testing a server listening to a given IP and port with the TCP protocol.

Futhermore, you could also try to ping the IP:

Ping ping = new Ping();
PingReply pingReply = ping.Send("192.168.0.200");

if (pingReply.Status == IPStatus.Success)
{
    // Server is alive
}

Ping class is located in System.Net.NetworkInformation.

Upvotes: 25

The accepted answer already gets the job done but for completeness the following method can be used asynchronously and supports timeout:

public async Task<bool> PingHostAndPort(string host, int port, int timeout)
{
    using (var tcpClient = new TcpClient()) // TcpClient is IDisposable
    {
        Task connectTask = tcpClient.ConnectAsync(host, port);
        Task timeoutTask = Task.Delay(timeout);
        // Double await is required to catch the exception.
        Task completedTask = await Task.WhenAny(connectTask, timeoutTask);
        try
        {
            await completedTask;
        }
        catch (Exception)
        {
            return false;
        }

        if (timeoutTask.IsCompleted)
        {
            return false;
        }

        return connectTask.Status == TaskStatus.RanToCompletion && tcpClient.Connected;
    }
}

Note that the timeout value is in milliseconds. To use the method:

bool success = await PingHostAndPort("host", 80, timeout: 3000);

Upvotes: 2

Related Questions