Using socket to test a TCP port

Hello,
I'm trying to write a small c application to test a tcp port. This works fine for the most part but the default timeout on the connect is very long. I have been reading many posts but and it looks like I need to set the socket to be non-blocking and poll for a result. I have been totally unable to make this work.

Does anyone have a quick example on setting up a timeout on a socket connect?

Thanks,
tom

What sort of timeout are you referring to? As I recall, tcp sockets do not have a connection time timeout, that is application level. Are you writing the server or the client? For server bind, you use SOCKOPT_REUSEADDR so you can bind while old connections are still in post connection timeout. After a socket is closed, there is still the possibility that buffered data is yet to be written (controlled by the linger option) or the fin ack may be lost and a second fin will arrive asking for another fin ack, so there is a latent structure for the connection still active for a time.

Assuming that you're implementing a TCP client, you have the following possibilities:

1) The connect() is carried out in a separate thread; another thread implements the timer. Upon timeout, the connect thread can be cancelled since connect() is a cancellation point.

2) You raise a signal when a timer expired to the thread calling connect(). This will cause connect() to be interrupted. Only useful for single threaded program; for multi-threaded program use 1) or 3).

3) You use non blocking socket, see a the snippet below

flags=fcntl(fd, F_GETFL, 0);
fcntl(fd, F_SETFL, flags | O_NONBLOCK);
connect(fd,&addr,len);
...

Then you need to poll() for both read/write events:

struct pollfd fds;
fds.fd = fd;
fds.events = POLLIN | POLLOUT;
poll(&fds,1,timeout)
...

Error checking is omitted for your convenient (DISCLAIMER: DON'T do this for production code)

HTH, Lo�c