ICMP and InetAddress.isReachable()

In Java it is only possible to work with two types of sockets: stream based ones (or TCP ones - java.net.Socket andjava.net.ServerSocket) and datagram based ones (or UDP ones -java.net.DatagramSocket and java.net.MulticastSocket).
The open bug 4727550 asks to support other socket types, that will allow, for example, to perform an ICMP ping and, in general, to access the sockets in raw mode.

To implement an ICMP ping, a partial solution has been introduced in J2SE 5: a way to check if some address is reachable, viajava.net.InetAddress.isReachable() methods.
The implementation of these methods goes native and tries to do its best to "ping" the address represented by the InetAddress.

Surprisingly, there are many differences between the Windows and the Linux/Unix implementation ofjava.net.InetAddress.isReachable().

Windows, as strange as it seems, does not officially support an ICMP "ping" system call. The J2SE 5 implementation hence tries to open a TCP socket on port 7 (the echo service) and hopes to get some sort of reply.

Linux/Unix, instead, supports an ICMP "ping" system call. So the implementation of java.net.InetAddress.isReachable() first tries to perform the "ping" system call; if this fails, it falls back trying to open a TCP socket on port 7, as in Windows.

It turns out that in Linux/Unix the ping system call requires root privileges, so most of the times java.net.InetAddress.isReachable()will fail, because many Java programs are not run as root, and because the target address unlikely has the echo service up and running. 
Too bad.

But why on Linux, for example, I can use the ping program without being root ? 
It's because ping has the setuid bit set:


$> ls -l /bin/ping
-rwsr-xr-x 1 root root 30724 2005-11-11 01:15 /bin/ping


When a user invokes ping, it will run as root (see the "rws" permission for the owner ?).

But why on Windows there is a ping executable that does the job ?
It seems that this executable is relying on undocumented features, so everyone tries to avoid binding to those features.

So, for now, writing portable Java code that wants to send ICMP ping is quite an adventure.

转载于:https://www.cnblogs.com/reynold-lei/p/3157966.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值