Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UDP Socket Set Timeout

Tags:

c

sockets

udp

I am trying to set a 100ms timeout on a UDP Socket. I am using C. I have posted relavent pieces of my code below. I am not sure why this is not timing out, but just hangs when it doesn't receive a segment. Does this only work on sockets that are not bound using the bind() method?

#define TIMEOUT_MS      100     /* Seconds between retransmits */  if ((rcv_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)     DieWithError("socket() failed");  if ((rcv_sock = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP)) < 0)     DieWithError("socket() failed");  //set timer for recv_socket static int timeout = TIMEOUT_MS; setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO,(char*)&timeout,sizeof(timeout));  if(recvfrom(rcv_sock, ackBuffer,sizeof(ackBuffer), 0,        (struct sockaddr *) &servAddr2, &fromSize) < 0){     //timeout reached     printf("Timout reached. Resending segment %d\n", seq_num);     num_timeouts++; } 
like image 640
rharrison33 Avatar asked Nov 25 '12 02:11

rharrison33


People also ask

How do I change my socket timeout?

You can use the SO_RCVTIMEO and SO_SNDTIMEO socket options to set timeouts for any socket operations, like so: struct timeval timeout; timeout. tv_sec = 10; timeout.

Do UDP sockets need to be closed?

Close the socket Since there is no concept of a connection in UDP, there is no need to call shutdown.

What is a socket timeout?

socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.

Do UDP sockets need to bind?

As far as I remember bind is not required for a UDP socket because a bind call is made for you by the stack.


1 Answers

The SO_RCVTIMEO option expects a struct timeval defined in sys/time.h, not an integer like you're passing to it. The timeval struct has as field for seconds and a field for microseconds. To set the timeout to 100ms, the following should do the trick:

struct timeval tv; tv.tv_sec = 0; tv.tv_usec = 100000; if (setsockopt(rcv_sock, SOL_SOCKET, SO_RCVTIMEO,&tv,sizeof(tv)) < 0) {     perror("Error"); } 
like image 107
Neal Avatar answered Sep 20 '22 11:09

Neal