Groppe
Groppe

Reputation: 3879

Calling select() on a UDP socket gives an invalid argument error

I am calling select() on a UDP socket to see if there is data to be read. Every time the method returns -1 and errno is set to 22 (Invalid Argument). Here is part of my code:

fd_set sockets;
struct timeval alarm;
alarm.tv_sec = 0;
alarm.tv_usec = 1000;
FD_ZERO(&sockets);
FD_SET(udpSocket, &sockets);
maxfd = udpsocket + 1;
selected = select(maxfd, &sockets, NULL, NULL, &alarm);
printf("%d\n", selected);

"Selected" is always -1. I know that the socket is fine because at this point I have already successfully sent data over it.

Upvotes: 0

Views: 1289

Answers (2)

Groppe
Groppe

Reputation: 3879

It turns out that the reason for the error was that I was setting the microseconds property of the alarm to:

alarm.tv_usec = 2000000;

Which apparently is too high a value. Obviously, it was just easier to set the seconds property to 2:

alarm.tv_sec = 2;

Upvotes: 2

Chris Dodd
Chris Dodd

Reputation: 126203

Accroding to the manual page for select, EINVAL means "nfds is negative or the value contained within timeout is invalid", which suggests that udpsocket is -2 or less.

One possible hint: you set udpSocket in the fd_set and then use udpsocket to calculate maxfd. Having two variables that differ only in the case of a single character is easy to miss.

Upvotes: 2

Related Questions