I am trying to implement the the timeout mechanism in my c implementation of TFTP, and i am looking for some general help.
What I am wondering is how to manage the timeout situation. The premature timeout mechanism that I used is with signal/alarm functions, but somehow I am stuck in how to handle my timeouts, that is if the packet (ack or data) is missed and a timeout occurs how to send back the previous packet or ack to the server.
Avoid signal and alarm if possible.
Either use SO_RCVTIMEO socket option or just use select with a timeout of T seconds.
If the select() call returns and your socket is not in the read set, or if recvfrom returns with a timeout error, then you can take appropriately action in your code.
Example of timeout usage:
timeval tv = {0,0};
tv.tv_sec = 5;
socklen_t optionlength = sizeof(tv);
setsockopt(s, SOL_SOCKET, SO_RCVTIMEO, &tv, optionlength);
while (1)
{
result = recvfrom(s, buffer, bufferlength, 0);
if (result == -1) && ((errno == EAGAIN) || (errno == EWOULDBLOCK)) )
{
// handle timeout
}
else if (result == -1)
{
// handle critical error
}
else
{
// process next packet
}
}
Example of select usage:
while (1)
{
timeval tv = {0,0};
tv.tv_sec = 5;
fd_set readset = {};
FD_ZERO(&readset);
FD_SET(s, &readset);
select(s+1, &readset, NULL, NULL, &tv);
if (FD_ISSET(s, &readset))
{
result = recvfrom(s, buffer, bufferlength, 0);
if (result == -1)
{
// handle error
}
else
{
// process packet
}
}
else
{
// handle timeout
}
}