Search code examples
csocketstimeout

Socket: Connect will spend 2 minutes looking for IP before it timesOut. How to reduce that time?


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


Solution

  • 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.