Mon
20
Dec '04
Send ICMP (ping) in Java 1.5
by Frank Spychalski filed under articles, Java, Work

If you find this useful, you might like my other articles, too.

Problem:

I tried to ping from a Java Application (via InetAdress.isReachable(…)) but no ICMP packets were sent, a fact I verified with tcpdump. The Javadoc for isReachable says “A typical implementation will use ICMP ECHO REQUESTs if the privilege can be obtained“.

Solution:

Under Linux you have to be root to be able to ping. If you look at ping and fping binaries you will notice the “s” which means the SETUID bit is set for these applications and they are executed with the userid of their owner which is root:

$ ls -l /usr/bin/fping /bin/ping
-rwsr-xr-x  1 root root 30764 Dec 22  2003 /bin/ping
-rwsr-xr-x  1 root root 22356 Oct  8 13:32 /usr/bin/fping

You have to change the owner of java to root (which was not necessary in my case) (chown root:root path/to/your/java) and set to set the SETUID bit for the java executable with (chmod +s path/to/your/java)

Warning!

I’m sorry to say, that this solution is a security risk and a major fuckup waiting to happen, because java is now always running as root! What I did is copy java to javaRoot and set the correct permissions, so I can use it if I’m 100% sure the application really must have root priviliges. But this is only a workaround and not a clean solution.

$ ls -l java*
-rwxr-xr-x  1 root root  64492 Sep 15 13:35 java
-rwsr-sr-x  1 root root  64492 Nov 22 13:56 javaRoot

addon 22.4.05
BTW, I don’t use isReachable anymore. I wrote a wrapper for fping. Why? Because isReachable sucks, if you want more then the simple information if a target is reachable or not, it’s a major PITA to figure out the response times and packet loss.


4 Responses to “Send ICMP (ping) in Java 1.5”

  1. 1

    and what about windows ?
    how to do under windows ?

    Diwann (April 21st, 2005 at 23:14)
  2. 2

    Sorry, I don’t know. I do all of my software development under Linux.

    Frank Spychalski (April 22nd, 2005 at 08:14)
  3. 3

    I implemented a real ICMP for Java with native support for win32, and I put it up on http://www.shortpasta.org — here is some sample code:

    final IcmpPingResponse icmpPingResponse =
    IcmpUtil.executeIcmpPingRequest (
    final String ipAddress,
    final int packetSize,
    final long timeout);

    Shortpasta (January 26th, 2010 at 02:46)
  4. 4

    Does anybody have any idea to implement an ICMP ping with C Sockets (BSD Sockets)???

    Manohar Kuse (September 30th, 2010 at 07:29)

Any comments? Or questions? Just leave a Reply: