2

How do I get the file descriptor of a Java Datagram socket? I've searched the web without any success.

Srini

Srini
  • 21
  • 2

3 Answers3

6

Old question, but for anyone else that comes across this, you do it like this...

DatagramSocket socket = ....();
ParcelFileDescriptor pfd = ParcelFileDescriptor.fromDatagramSocket(socket);
FileDescriptor fd = pfd.getFileDescriptor();
Kaleb
  • 1,855
  • 1
  • 18
  • 24
0

You would need a custom factory to return a custom subclass of DatagramSocketImpl that had a public get function for the file descriptor.

bmargulies
  • 97,814
  • 39
  • 186
  • 310
0

You can retrieve the FileDescriptor using Reflection. Following works for Sun-Java

public static FileDescriptor getFileDescriptor(DatagramSocket ds)
{
    try
    {
        final Field fimpl = ds.getClass().getDeclaredField("impl");
        fimpl.setAccessible(true);
        final DatagramSocketImpl impl = (DatagramSocketImpl) fimpl.get(ds);
        final Method gfd = DatagramSocketImpl.class.getDeclaredMethod("getFileDescriptor",
                new Class<?>[0]);
        gfd.setAccessible(true);
        return (FileDescriptor) gfd.invoke(impl);
    }
    catch (final Exception e)
    {
        e.printStackTrace();
        return null;
    }
}

The native socket may be extracted by

public static int FdToInt(FileDescriptor fd)
{

    try
    {
        final Field ffd = FileDescriptor.class.getDeclaredField("fd");
        ffd.setAccessible(true);
        return (Integer) ffd.get(fd);
    }
    catch (final Exception e)
    {
        e.printStackTrace();
        return -1;
    }

}
Sam Ginrich
  • 661
  • 6
  • 7