Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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