How can I retry sending (let's say using a while loop or something similar) in the following code that I have, whenever I have a timeout? I abridged some parts of my code.
I am not familiar with C error codes and error handling so I don't know where to catch/handle the error and what error code to look for.
sock = socket(create socket....)
if (sock < 0 ) {
exit(EXIT_FAILURE);
}
servaddr initializations.....
sendto(sock, etc etc........);
struct timeval timeout;
timeout.tv_sec = 5;
timeout.tv_usec = 0;
if (setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO,&timeout,sizeof(timeout)) < 0) {
perror("Error");
}
addrlen = sizeof(servaddr);
if(recvfrom (sock, etc, etc......) < 0)
{
printf("revfrom failed.\n");
}
From
man 7 socket
:So, in your case, the code to keep trying if the timeout is reached would look something like this:
Note that
SO_SNDTIMEO
is for sending, andSO_RCVTIMEO
is for receiving. If you want to set both then do twosetsockopt
calls.In any case, it seems to me like you are wasting your time with this. If you want to keep trying until you get data, then just don't bother doing any
setsockopt
, as the default behavior is to wait indefinitely until data is received: