Search code examples
javacsocketsjava-native-interfacefile-descriptor

Most efficient way to pass Java socket file descriptor to C binary file


I can't seem to find the answer anywhere, I'm trying to obtain a socket in Java, and hand over its file descriptor number so that I can use it in a C binary (the fd would be as argument).

I've obtained the FileDescriptor using reflection... but can't access the actual number anywhere.

I know other people have suggested JNI, but I'd like to keep it within Java if possible (and couldn't fully figure out how to do it)


Solution

  • In Java 7, you can cast a SocketInputStream to a FileInputStream, and call getFD() to get the FileDescriptor object.

    Then you can use reflection to access the FileDescriptor object's private int fd field. (You use the Class.getDeclaredField(...) method to get the Field, call Field.setAccessible(true), and then get the field's value using Field.getInt(...).)


    Beware that you may be making your code platform dependent by doing this. There are no guarantees that the particular private field will be present in older ... or forth-coming versions of Java, or in implementations of Java done by other vendors / suppliers.