C# - Avoid getting a SocketException

CudoX picture CudoX · May 2, 2013 · Viewed 7.7k times · Source

I was wondering if there's a way to avoid getting a SocketException whenever I cannot connect rather than catching the SocketException using try/catch.

I have this code which checks if a server is available of not:

public bool CheckServerStatus(string IP, int Port)
    {
        try
        {
            IPAddress[] IPs = Dns.GetHostAddresses(IP);

            using (Socket s = new Socket(AddressFamily.InterNetwork,
                SocketType.Stream,
                ProtocolType.Tcp))
            s.Connect(IPs[0], Port);

            return true;
        }
        catch (SocketException)
        {
            return false;
        }
    }

Thanks in advance.

Answer

Ahmed KRAIEM picture Ahmed KRAIEM · May 2, 2013

You may subclass Socket and provide your specific implementation:

public class MySocket : Socket{
    //...
    public boolean TryConnect(...){
    }
}

You could also instead of a boolean, return a Result object that save the exception for error handling:

public class Result {
    public Exception Error { get; set; }
    public boolean Success { get{ return Error != null; } }
}