How to set socket option (TCP_KEEPCNT, TCP_KEEPIDL

2019-05-03 01:44发布

问题:

In C/Linux, it's easily to set different value about those socket options for every KEEPALIVE tcp connection independently.

TCP_KEEPCNT (since Linux 2.4) The maximum number of keepalive probes TCP should send before dropping the connection. This option should not be used in code intended to be portable.

TCP_KEEPIDLE (since Linux 2.4) The time (in seconds) the connection needs to remain idle before TCP starts sending keepalive probes, if the socket option SO_KEEPALIVE has been set on this socket. This option should not be used in code intended to be portable.

TCP_KEEPINTVL (since Linux 2.4) The time (in seconds) between individual keepalive probes. This option should not be used in code intended to be portable.

In netty or java, how to set the three socket options for socket? I know there is no portable way to solve it, but only in Linux, can I set those socket options?

回答1:

The link given doesn't actually tell you how to use JNA to implement it. Having spent a while digging around on SO to find solutions, I wrote my own library. You can find it here.



回答2:

Recent versions of Netty allow you to use epoll type channels and set Linux-native socket options such as the ones you mentioned.

See the documentation of EpollChannelOption for details.



回答3:

It appears this is supported in Java 11, via new fields in the ExtendedSocketOptions class. These can be passed to the setOption method on either java.net.Socket or java.nio.channels.SocketChannel.

Note I have not actually tried using this. The docs explicitly say these are platform specific, so you'll need to test they actually do what you want on the platforms you care about.