Skip to content

Instantly share code, notes, and snippets.

@kstolte
Last active October 30, 2017 15:04
Show Gist options
  • Save kstolte/9b1c4d6d23a1b77be24dd634e6e7d6e5 to your computer and use it in GitHub Desktop.
Save kstolte/9b1c4d6d23a1b77be24dd634e6e7d6e5 to your computer and use it in GitHub Desktop.
There are many times when you are trying to connect to an service. Depending on what service you are trying to connect to, there may not be a short circuit when the Server is not available at all. The following will verify that the server is accepting connections on a specific port so that you can "ping" specifically to your intended use port. T…
using System.Net.Sockets;
private bool CheckForServer(string address, int port)
{
int timeout = 500;
var result = false;
try
{
using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
{
IAsyncResult asyncResult = socket.BeginConnect(address, port, null, null);
result = asyncResult.AsyncWaitHandle.WaitOne(timeout, true);
socket.Close();
}
return result;
}
catch { return false; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment