Before java 17, we could get the FD on a datagram socket like below trick with reflection, in order to set a socket option for SO_PORTREUSE using a kernel API. But the implementation changed in latest java and the field is now called delegate, and the setAccessible API will not work with it due to a java.lang.reflect.InaccessibleObjectException.
Has anyone found an alternative way to get this from the datagram socket?
private int getFD(DatagramSocket ds) throws Exception {
Field dsImpl = DatagramSocket.class.getDeclaredField("impl");
dsImpl.setAccessible(true);
Field fd = DatagramSocketImpl.class.getDeclaredField("fd");
fd.setAccessible(true);
FileDescriptor fdi = (FileDescriptor) fd.get(dsImpl.get(ds));
Field fdVal = FileDescriptor.class.getDeclaredField("fd");
fdVal.setAccessible(true);
return fdVal.getInt(fdi);
}
DatagramSocket.setOption()andSO_REUSEPORT. You don't need Reflection at all.