开发者

File descriptor of a java datagram socket

How do I get the file descriptor of a Java Datagram socket? I've search开发者_StackOverflowed the web without any success.

Srini


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


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


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

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜