Post by d-fanHow can I open a socket connection with a timeout? Currently when I
make a call like "var = socket(" if the internet is down or there is
a problem reaching the destination computer, my programs behaves like
it is freezing. It here a way to control this behavior via a timeout
or any other method so that if the destination cannot then my program
will not hang?
The socket() call should never hang. If it does it means either the OS
is very busy or theres something wierd happening.
I assume you're writing a client and mean connect() hangs? In which
case you can either spawn a seperate thread or process to run the
connect in , or you can set the socket to non blocking which means
connect() will return immediately and then you wait in a select() for
the write descriptor to be set. This can be quite tricky to code so
its probably best you buy a book such as Unix Network Programming or
similar. However some example code would be:
iif ((sock = socket(AF_INET,SOCK_STREAM,0)) == -1)
{
do something
}
flags = fcntl(sock,F_GETFL,0);
fcntl(sock,F_SETFL, flags | O_NONBLOCK)
if (!connect(sock,....))
{
got immediate connect
}
if (errno != EINPROGRESS)
{
perror("connect"); exit(1);
}
FD_ZERO(&wset);
FD_SET(sock,&wset);
timeout.tv_sec=1;
timeout.tv_usec=0;
/* Wait for write bit to be set */
switch (select(FD_SETSIZE,0,&wset,0,&timeout))
{
}
Obviously you'll need to fill in lots of code above but thats the
general idea of how to write a single threaded non blocking connect.
B2003