There is no portable way for a Java program to change the effective user id; i.e. change from running with root privilege to another user. (And even in C an application can't switch between privileged and non-privileged willy-nilly. Privilege switching is a one-way street.)
Reading the javadoc for InetAddress.isReachable
it does use different mechanisms depending on the JVM process's privilege. However, neither of the two approaches used by isReachable
is guaranteed to work; e.g.
- some firewall may selectively block ICMP ECHO messages,
- the target machine might not be running an Echo service on port 7 ... or port 7 may be locked by a firewall.
So I would address avoid issue entirely. Just try to do whatever it is that you are really trying to do, and forget about using isReachable
. Or if it is within your control, fix the machines / networks so that both mechanisms work for the machines you need to test.
@Geek - you say that you can't test particular ports because they can be blocked. Well anything can be blocked, including ICMP PING, ICMP ECHO and anything else that you might use to test if the host is reachable.
There is only one thing that really matters: can you talk to the service that you are actually going to use. And there is only one way to find out: try to use it.
Or to say it another way, testing if a host is available doesn't make sense. Hosts are not available: specific services are.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…