2

I want to reduce the allowed timeOut time that socket:connect will take to look up an IP/Port to connect to? On some network routers like Netgear that use IP 10.0.0.x only takes less than a second to timeout.

Note: "select" comes later

host = gethostbyname("xxx");//invalid IP, 

memcpy(&(sin.sin_addr), host->h_addr, host->h_length);
sin.sin_family = host->h_addrtype;
sin.sin_port = htons(4000);

s = socket(AF_INET, SOCK_STREAM, 0);
hConnect = connect(s, (struct sockaddr*)&sin, sizeof(sin));//sits here for 2 minutes before moving on to the next line of code

bConn = 0;// no connect
if (hConnect == 0) {
    bConn = 1;// connect made
}

thx

jdl
  • 6,151
  • 19
  • 83
  • 132
  • what OS are you using? Where's the rest of the code, I need to see a little bit more than this. Could you be a bit more vague? What is the question? – lukecampbell May 11 '12 at 18:12
  • 1
    There is an interesting asynchronous approach here: http://stackoverflow.com/q/1062035/694576 – alk May 11 '12 at 18:20
  • I am using a standard-c library... this repeats on PC or MAC or iPhone – jdl May 11 '12 at 18:35
  • here is an approach... but dangerous... put this in a thread, kill the thread in 5 seconds. If the local IP exists, it should connect in a fraction of a second. – jdl May 11 '12 at 18:50
  • 1
    possible duplicate of [C: socket connection timeout](http://stackoverflow.com/questions/2597608/c-socket-connection-timeout) – Adam Rosenfield May 11 '12 at 18:54
  • 1
    Btw: `gethostbyame()` and `gethostbyaddr()` are somehow deprecated. You might better use `getnameinfo()` and `getaddrinfo()` – alk May 11 '12 at 19:12
  • Here is a good example: http://developerweb.net/viewtopic.php?id=3196 – jdl May 11 '12 at 19:19

2 Answers2

3

Set the socket to non-blocking prior to calling connect(), and then do a select() or poll() on it to find out any events going on on it.

Note: Using this setup you'll be getting a non-zero return from connect() and errno is set to EINPROGRESS in the case connect() returns without having connected but still is trying to do.

Please see the ERRORS section of connect()'s man page for more on this.

alk
  • 69,737
  • 10
  • 105
  • 255
  • 1
    Yes sure, you do this also by using `setsockopt()` but not using `O_NONBLOCK`as for setting the non-blocking flag, but it's invers value `~O_NONBLOCK`... – alk May 11 '12 at 19:18
1

The standard way to do this is in two steps:

  1. connect() with O_NONBLOCK
  2. use select() with a timeout
Yusuf X
  • 14,513
  • 5
  • 35
  • 47