Brian Brian - 5 months ago 23
Linux Question

How to check if UDP packet received in C Linux

"recvfrom()" in below sample code waits until UDP packet is received.

But I need to check whether UDP packet is available or not.
If packet is not received, then continue other tasks.
If packet is received, then receive packet and parsing.
How can I do this in Linux c program? Please help!

for (;;)
{
printf("waiting on port %d\n", SERVICE_PORT);
recvlen = recvfrom(fd, buf, BUFSIZE, 0, (struct sockaddr *)&remaddr, &addrlen);
printf("received %d bytes\n", recvlen);
if (recvlen > 0) {
buf[recvlen] = 0;
printf("received message: \"%s\"\n", buf);
}
}

Answer

You can use select function to know a something is ready to be read on a socket.

while (1)
{
    int retval;
    fd_set rfds;
    // one second timeout
    struct timeval tv = {1,0};

    FD_ZERO(&rfds);
    FD_SET(fd, &rfds);

    retval = select(1, &rfds, NULL, NULL, &tv);

    if (retval == -1)
    {
        perror("select()");
        exit(1);
    }        
    else if (retval)
    {
        printf("Data is available now.\n");      
    }
    else
    {
        // no data to read... perform other tasks
    }
}