3

I tried to use SO_RCVTIMEO option to timeout when there is no data in recvfrom API. But this is not taking effect, and the code is stuck when there is no data from the source.

I even tried using recv instead of recvfrom. Still the same issue.

Please let me know if anything is missing in my code.

int sock_r=socket(AF_PACKET,SOCK_RAW,htons(ETH_P_ALL)); 
if(sock_r<0)
{
    printf("open_raw_socket(): error in opening the socket");
    return -1;
}

struct timeval tv;
tv.tv_sec = 1;
tv.tv_usec =  0;
int ret = setsockopt(sock_r, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
perror("error: ");

socklen_t ntrcv, ntsnd; 
struct timeval trcv;   
ntrcv = sizeof(struct timeval); 
if (getsockopt(sock_r, SOL_SOCKET, SO_RCVTIMEO, &trcv, &ntrcv) < 0) 
{
    perror("2");
    TF_MSG("error");
}  

while(1)
{
    saddr_len=sizeof saddr;
    recv_len = recvfrom(sock_r,buffer,buflen,0,&saddr,(socklen_t *)&saddr_len);


    if(recv_len<=0)
    {
        printf("error in reading recvfrom function");
        return 0;
    }
.....
stark
  • 12,615
  • 3
  • 33
  • 50
  • Don't call `perror()` unless there *was* an error, e.g. at `setsockopt()`, and *do* call it if there was, e.g. at `socket()` and `recvfrom()`. *Was* there an error? And what was the value in `trcv` returned by `getsockopt()`? – user207421 Sep 25 '19 at 06:53
  • i changed the perror() as mentioned. Only if setsockopt() is returning value < 0, perror() is added. trcv was returning correct value. Both seconds and usec were holding the correct value. Just that it was not taking any effect – vidhiya lakshmi Sep 25 '19 at 12:09
  • Rather than using `SO_RCVTIMEO` at all, you can use `select()`/`(e)poll()` with a timeout to wait for data to arrive before then calling `recv/from()` to read it – Remy Lebeau Sep 26 '19 at 00:20
  • Hi Remy Lebeau, I tried the below code. In this attempt, no data was received even when other side pumps the data. struct pollfd fd; int ret; fd.fd = sock_r; // your socket handler fd.events = POLLIN; ret = poll(&fd, 1, 1000); // 1 second for timeout switch (ret) { case -1: printf("ret value for poll : -1"); break; case 0: printf("ret value for poll : 0"); break; default: recv_len = recv(sock_r,buffer,buflen, 0 ); // get your data break; } – vidhiya lakshmi Sep 26 '19 at 09:53

0 Answers0