Skip to content

Instantly share code, notes, and snippets.

@esdrubal
Created December 19, 2014 13:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save esdrubal/4316507e12fefdb7bc63 to your computer and use it in GitHub Desktop.
Save esdrubal/4316507e12fefdb7bc63 to your computer and use it in GitHub Desktop.
private void ExecutePortScan(string host, int port, int timeout)
{
using (TcpClient tcpClient = new TcpClient())
{
DateTime timer = DateTime.Now;
TimeSpan time;
IAsyncResult result = tcpClient.BeginConnect(host, port, null, null);
WaitHandle timeoutHandler = result.AsyncWaitHandle;
try
{
if (!result.AsyncWaitHandle.WaitOne (new TimeSpan (0, 0, timeout), false)) {
tcpClient.Close ();
time = DateTime.Now - timer;
Console.WriteLine (time.ToString () + " " + "Timeout expired");
} else {
tcpClient.EndConnect(result);
time = DateTime.Now - timer;
Console.WriteLine(time.ToString() + " " + "Success");
}
}
catch (Exception ex)
{
time = DateTime.Now - timer;
Console.WriteLine(time.ToString() + " " + ex);
}
finally
{
timeoutHandler.Close();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment