Introduction
Connecting to a C# socket with a timeout, without using asynchronous (ConnectAsync).
Background
When connecting to a socket in C# synchronously you don’t have a default timeout
property. And usually if the server is down then it
takes a long time to timeout. In order to overcome this I have come up with a simple solution.
Using the code
The below block of code will allow you to connect to a socket with a timeout.
private bool CheckConnectivityForProxyHost(string hostName, int port)
{
if (string.IsNullOrEmpty(hostName))
return false;
bool isUp = false;
Socket testSocket = null;
try
{
testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPAddress ip = null;
if (testSocket != null && IPAddress.TryParse(serverNameOrURL, out iP))
{
IPEndPoint ipEndPoint = new IPEndPoint(ip, port);
isUp = false;
CallWithTimeout(ConnectToProxyServers, 5000, testSocket, ipEndPoint);
if (testSocket != null && testSocket.Connected)
{
isUp = true;
}
}
}
}
catch (Exception ex)
{
isUp = false;
}
finally
{
try
{
if (testSocket != null)
{
testSocket.Shutdown(SocketShutdown.Both);
}
}
catch (Exception ex)
{
}
finally
{
if (testSocket != null)
testSocket.Close();
}
}
return isUp;
}
private void CallWithTimeout(Action<Socket, IPEndPoint> action,
int timeoutMilliseconds, Socket socket, IPEndPoint ipendPoint)
{
try
{
Action wrappedAction = () =>
{
action(socket, ipendPoint);
};
IAsyncResult result = wrappedAction.BeginInvoke(null, null);
if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
{
wrappedAction.EndInvoke(result);
}
}
catch (Exception ex)
{
}
}
private void ConnectToProxyServers(Socket testSocket, IPEndPoint ipEndPoint)
{
try
{
if (testSocket == null || ipEndPoint == null)
return;
testSocket.Connect(ipEndPoint);
}
catch (Exception ex)
{
}
}
bool isConnected = CheckConnectivityForProxyHost("192.168.1.100", 1010);
Reminders
This will work fine for .NET 4.0.