Skip to main content

Example C# program to test whether a TCP connection is available.

using System;
using System.Diagnostics;
using System.Net;
using System.Net.Sockets;

namespace IsConnectable
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            const string hostNameOrIpAddress = "jonlabelle.com";
            const int port = 443;
            const int millisecondsTimeout = 1000;

            bool isConnectable = false;

            using (TcpClient client = new TcpClient())
            {
                try
                {
                    if (client.ConnectAsync(hostNameOrIpAddress, port).Wait(millisecondsTimeout))
                    {
                        isConnectable = true;
                        client.Close();
                    }
                    else
                    {
                        Console.WriteLine("The connection attempt has timed out after " +
                                          "waiting {0}ms for the server to respond.{1}",
                                          millisecondsTimeout, Environment.NewLine);
                    }
                }
                catch (ArgumentNullException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch (ArgumentOutOfRangeException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch (SocketException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch (ObjectDisposedException ex)
                {
                    Console.WriteLine(ex.Message);
                }
                catch (AggregateException ex)
                {
                    Exception baseException = ex.GetBaseException();
                    Console.WriteLine(baseException.Message);
                }
            }

            Console.WriteLine("{0}:{1} is{2}connectable.",
                              hostNameOrIpAddress, port,
                              (isConnectable ? " " : " NOT "));

            Console.WriteLine();
            Console.WriteLine("Press any key to exit...");
            Console.WriteLine();
            Console.ReadKey();
        }
    }
}