I fallen into problem during development of my client application.
I want to use non-blocking UDP sockets in my application to communicate with a server. I am using winsock2
library on Windows.
But... For some reason I have strange behavior of select()
function under some conditions:
- Socket don't have bound address and port (it is client-side socket, so it don't need it).
- Before
select()
I send data to my local address and some port withsendto
call.- For example:
192.168.1.2
- For example:
Under these conditions select()
instantly (without even waiting for timeout) returns 1
. Like I have some packet ready to receive.
But if call recvFrom
then it will sure return -1
.
- If I send my packets from client to any other address (which is not my address on LAN) then
select()
works as intended. - Also
select()
works as intented if don't send any packets to any address before callingselect()
.
Socket initialization method:
bool CUdpSocket::initialize()
{
_handle = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
... error processing code, returns false if error...
}
Method which uses select()
. This method works fine for server socket (with bound address and port).
bool CUdpSocket::waitData(s32 timeout_ms)
{
fd_set readset;
int result;
struct timeval tv;
// Initialize the set.
FD_ZERO(&readset);
FD_SET(_handle, &readset);
// Initialize time out struct.
tv.tv_sec = 0;
tv.tv_usec = timeout_ms * 1000;
result = select(_handle + 1, &readset, NULL, NULL, &tv);
// Timeout with no data.
if (result == 0) {
return false; // Get out of here!
}
// Error.
if (result < 0) {
// TODO: Maybe throw exception or do something.
return false;
} else if (!FD_ISSET(_handle, &readset)) {
return false; // No data!
}
// There is some data!
return true;
}
recvfrom()
will return -1 with what error? – user207421recvFrom
call returns code 10054 (WSAECONNRESET). – zcaliptium