#include
#include
#include
#include
#include
#include
I had the same problem; and the is due to the fact that the udp message queue is filled if nobody is listening and emptying the queue.
According to the linux man page for udp:
All fatal errors will be passed to the user as an error return even when the socket is not connected. This includes asynchronous errors received from the network. You may get an error for an earlier packet that was sent on the same socket. This behaviour differs from many other BSD socket implementations which don't pass any errors unless the socket is connected. Linux's behaviour is mandated by RFC 1122.
Specifically the RFC (4.1.3.3) states:
UDP MUST pass to the application layer all ICMP error messages that it receives from the IP layer. Conceptually at least, this may be accomplished with an upcall to the ERROR_REPORT routine
To start at the other end, if you connect a UDP socket you can collect errors on the next send. If you don't want that, don't connect!
Your hypothesis is correct. The Linux udp(7) man page describes the situation thus:
All fatal errors will be passed to the user as an error return even when the socket is not connected. This includes asynchronous errors received from the network. You may get an error for an earlier packet that was sent on the same socket.
This behavior differs from many other BSD socket implementations which don't pass any errors unless the socket is connected. Linux's behavior is mandated by RFC 1122.When the
IP_RECVERR
option is enabled all errors are stored in the socket error queue and can be received byrecvmsg(2)
with theMSG_ERRQUEUE
flag set.
It would be interesting to compare the equivalent code using sendto()
rather than connect()
and send()
.
Does the code shown fail in the same way if you leave a period of time between each send, i.e. is the ICMP error state being kept in the socket for a period of time, or would it still fail the second send()
if you left it, say, an hour?
I expect that your assumption is correct, the network stack is trying to be clever. There's no other point when it could return 'connection refused' as nothing is sent when the connect()
call is issued it simply stores the address given so that the socket is 'logically' connected and calls to send()
can then work.