Search code examples
socketsudpfreebsdbsd

Determining the size of the next UDP datagram in BSD platforms?


In Linux I can use an ioctl call with FIONREAD to get the number of bytes for the next UDP packet.

That doesn't work on OSX and instead I have to use getsockopt call with SO_NREAD to determine the number of bytes for the packet.

Is there a way I can avoid doing a peek or a read into a big buffer followed by a copy to achieve the same result under BSD platforms?


Solution

  • FIONREAD works in BSD. In fact that's where it came from. But it returns the total number of bytes available to be read without blocking, which could be more than one datagram.

    EDIT You could try using MSG_PEEK|MSG_TRUNC and supplying a buffer length of zero, or one if it doesn't like that. It should return you the real length.