can I read exactly one UDP packet off a socket?

The accepted answer doesn't clearly answer the OP's question, because it mentions buffer size only in passing.

I'm currently reading packets off a non-blocking socket using recvmsg, with a buffer size a little larger than the MTU of our internal network.

It's important for your buffer to be big enough to fit one entire datagram. A datagram can be up to 65,536 bytes. When a large datagram is fragmented because of MTU it will be reassembled by the stack, you won't know about this, you will just receive nothing until all the fragments are received and put back together into the original datagram. If you make your buffer slightly bigger than one MTU, for instance 1600 bytes, and you call recv() on an incoming datagram that is 40K bytes, you will get just the first 1600 bytes.


recvmsg will return you one packet, and it will be the entire packet (as long as the buffer you provide it is large enough).

From the POSIX documentation:

The recvmsg() function shall receive a message from a connection-mode or connectionless-mode socket.

"a message" means exactly one message (or packet), and,

For message-based sockets, such as SOCK_DGRAM and SOCK_SEQPACKET, the entire message shall be read in a single operation.

Tags:

C

Udp