Last active
October 30, 2017 15:04
-
-
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…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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