diesel10
diesel10

Reputation: 1

How to get FD on datagram socket?

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);
    }

Upvotes: 0

Views: 66

Answers (1)

diesel10
diesel10

Reputation: 1

It appears that using the opens JVM flags we can get this work with java 17 again.

--add-opens=java.base/java.io=ALL-UNNAMED 
--add-opens=java.base/java.net=ALL-UNNAMED 
--add-opens=java.base/sun.nio.ch=ALL-UNNAMED 
--add-opens java.base/java.lang=ALL-UNNAMED 
--add-opens java.base/java.util=ALL-UNNAMED

Upvotes: -2

Related Questions