No Support for "Don't Fragment" Bit in Datagram Channels in Java NIO

I’m currently working with Java NIO and facing a challenge with Datagram channels. I need to set the “Don’t Fragment” bit for UDP packets, but I’ve discovered that there’s no option available in Java NIO to do this.

Unlike other platforms that provide support for setting this bit directly (for example, using setsockopt in C++ for BSD Sockets), Java NIO’s DatagramChannel doesn’t expose any socket options that would allow for this configuration. I’ve looked through the available options, and it seems we’re limited in this regard. Can anyone guide me on how can I achieve this using Java NIO?

NOTE: My intentions for using Don’t Frag bit is to discard any packets which are greater than MTU and only send packets which are less than or equal to the MTU.

Not tried so I don’t know whether this actually works, but you could try to get the FileDescriptor out of the socket :

val fd = ParcelFileDescriptor.fromDatagramSocket(socket)?.getFileDescriptor()

Then use Os.setSockoptInt with the appropriate values.

Os.setSockoptInt is meant exactly for this kind of use case where the API doesn’t have the exact sock opt that you need but you actually know what you’re doing.

That being said I expect there is good reason this is much harder than you’d expect, as in it probably doesn’t actually do what you expect. The values may be platform-dependant (e.g. imagine the value you need to pass depends on the OEM of the phone), and likely it’s actually ignored by a lot of middle boxes out there (which may happily fragment anyway).

You don’t give a lot of detail on what you’re writing (is this a middle box, is this a VPN app or something ?) or why you want to do this specifically ; I get that if an app sends a packet bigger than the MTU with the don’t fragment flag it’s making a risky bet about what might happen to the packet, but if an app transmits a packet it’s because it hopes the packet will make it to the other side so hard drop tends to interfere with best app behavior. But obviously this depends on what kind of software you’re writing. So I’m left wondering what the background is.