jdl
jdl

Reputation: 6333

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

Upvotes: 2

Views: 565

Answers (2)

alk
alk

Reputation: 70981

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.

Upvotes: 3

Yusuf X
Yusuf X

Reputation: 14633

The standard way to do this is in two steps:

  1. connect() with O_NONBLOCK
  2. use select() with a timeout

Upvotes: 1

Related Questions