public static void Connect(Socket socket, EndPoint endPoint, int timeoutMs) { var connectCall = new TcpConnectCall(socket); try { //Need for controlling timeout period introduces us to assynccallback methods var connectedCallback = new AsyncCallback(connectCall.ConnectedCallback); var result = socket.BeginConnect(endPoint, connectedCallback, connectCall); // wait for timeout for connect if (result.AsyncWaitHandle.WaitOne(timeoutMs, false) == false) { connectCall.CancelConnect(); // throw exception throw new Exception("TIME_OUT"); } else { if (connectCall._mConnectCallbackCompleted.WaitOne(15000, false) == false) { } Exception connectException = connectCall._mConnectFailureException; if (connectException != null) { //throw new Exception("Exception occurred during connect attempt: " + connectException.Message, connectException); throw new Exception("PORT_CLOSED"); } } } finally { connectCall.Dispose(); } }
private string TCPScan(int port, IPEndPoint ipEnd) { try { TcpConnectCall.Connect(new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp), ipEnd, Convert.ToInt32(textBox6.Text)); return(string.Format("{0} is opened\n", port)); } catch (Exception ex) { switch (ex.Message) { case "TIME_OUT": return(string.Format("{0} is filtered\n", port)); break; case "PORT_CLOSED": return(string.Format("{0} is closed\n", port)); break; } } return(null); }