开发者

setsockopt in Java programs

开发者 https://www.devze.com 2023-03-08 18:58 出处:网络
From version 8 onwards FreeBSD supports IP_BINDANY socket option which the man page defines as: If the IP_BINDANY option is enabled on a SOCK_STREAM, SOCK_DGRAM or a

From version 8 onwards FreeBSD supports IP_BINDANY socket option which the man page defines as:

If the IP_BINDANY option is enabled on a SOCK_STREAM, SOCK_DGRAM or a SOCK_RAW socket, one can bind(2) to any address, even one not bound to any available network interface in the system. This functionality (in conjunction with special firewall rules) can be used for implementing a transparent proxy. The PRIV_NETINET_BINDANY privilege is n开发者_运维问答eeded to set this option.

Is it possible to write a Java program that can use this functionality? I have checked the docs of SocketOptions and it obviously does not list this option. So is there any workaround?

with regards,

raj


Is it possible to write a Java program that can use this functionality?

It is not possible using a pure Java.

So is there any workaround?

There are a couple of JNA/JNI based libraries for making Posix system calls from a Java program; see this SO question/answer for details:

  • Is there a Java library of Unix functions?

I don't know if these are available for Java on FreeBSD.


On further thought, it might be possible to implement this in pure (though necessarily non-portable) Java. It would entail creating subclasses of SocketImpl and/or DatagramSocketImpl and the necessary infrastructure to use them. It would be complicated.


I wrote a library in JNA to do the setsockopt bit reasonably portably. You can find it here.

However, to change the bind behaviour you may need to dig further into the socket code. For why, see here, specifically this bit:

So we just need to create a new java.net.Socket object, call setsockopt() and finally call bind() on the socket - easy, right? Unfortunately, it’s not quite so simple - creating a new Socket object in Java (in OpenJDK and the Oracle JVM) does not actually allocate a file descriptor. Instead, the file descriptor is allocated within Java’s bind() function itself - making it rather difficult to call setsockopt() at the appropriate point.

The author presents a reasonably complex workaround - I'm not going to copy his entire article here though.

0

精彩评论

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