When I try to connect to a server with a non blocking socket (so that i can use select() with a timeout parameter) i realized that on a connect to a port which is blocked by iptables with -j REJECT the select() waits up to the timeout parameter but at a maximum of 3s.. it doesn't matter that the ICMP port unreachable packet is really quick.
fcntl(sockfd, F_SETFL, O_NONBLOCK);
connect(sockfd,(struct sockaddr *) &serv_addr,sizeof(serv_addr));
if (select(sockfd + 1, NULL, &fdset, NULL, NULL) == 1) {...}
In the above example the select() blocks until 3s if the connect goes to localhost:1234 and the port is blocked like described above.
Does anyone know why this timeout of 3s to get a "connection refused"? How could I tweak it (because I got an ICMP port unreachable after 0.02ms)?
The socket will only become "writable" if
connect
succeeds. If you also wantselect
to return on failure, you should also check for "error/exceptional" condition on the socket, i.e. pass the set as the thirdfd_set *
argument toselect
too.