1

Is it possible to set a timeout when performing a port lookup as demonstrated in the code below?:

    try
    {
        System.Net.Sockets.Socket sock = new System.Net.Sockets.Socket(System.Net.Sockets.AddressFamily.InterNetwork, System.Net.Sockets.SocketType.Stream, System.Net.Sockets.ProtocolType.Tcp);
        sock.Connect(ipa, portno1);
        if (sock.Connected == true) // Port is in use and connection is successful
        {
            displayGreen1();
        }
        sock.Close();

    }
Mike
  • 2,266
  • 10
  • 29
  • 37
  • 3
    This is a repeat of http://stackoverflow.com/questions/456891/how-do-i-set-the-time-out-of-a-socket-connect-call – robowahoo Oct 24 '11 at 20:58

3 Answers3

3

Use code taken from here

Socket socket = new Socket(
    AddressFamily.InterNetwork, 
    SocketType.Stream, 
    ProtocolType.Tcp);

// Connect using a timeout (5 seconds)
IAsyncResult result = socket.BeginConnect(sIP, iPort, null, null);
bool success = result.AsyncWaitHandle.WaitOne(5000, true);
if (!_socket.Connected)
{
    // NOTE, MUST CLOSE THE SOCKET
    socket.Close();
    throw new ApplicationException("Failed to connect server.");
}
Community
  • 1
  • 1
Marco
  • 56,740
  • 14
  • 129
  • 152
0

FYI...

Socket tcpSocket;

// Set the receive buffer size to 8k
tcpSocket.ReceiveBufferSize = 8192;

// Set the timeout for synchronous receive methods to 
// 1 second (1000 milliseconds.)
tcpSocket.ReceiveTimeout = 1000;

// Set the send buffer size to 8k.
tcpSocket.SendBufferSize = 8192;

// Set the timeout for synchronous send methods
// to 1 second (1000 milliseconds.)            
tcpSocket.SendTimeout = 1000;
Siva Charan
  • 17,940
  • 9
  • 60
  • 95
0

Looks like this may be what you're looking for: http://www.codeproject.com/KB/IP/TimeOutSocket.aspx.

It seems that he's using

    ManualResetEvent.WaitOne()

to block the main thread for the duration of the time-out. If

    IsConnectionSuccessful

is false (i.e., the connection was not made in time or the callBack failed) when time runs out, an exception will be thrown.

Drew Gaynor
  • 8,292
  • 5
  • 40
  • 53
  • @PeterManton Good for just **one** port lookup. If your intension is `port scanning` forget it. – L.B Oct 24 '11 at 21:40