Root Permissions Required to Send ICMP Echo Request From Java using <tt>java.net.InetAddress</tt>

Posted by Tres Mon, 12 May 2008 09:31:00 GMT

Since Java 5, we’ve been able to send ICMP Echo requests using java.net.InetAddress; however, under *nix like systems, you’ll need root level permissions to get things running. If you don’t have the correct system permissions, java.net.InetAddress will silently fail, letting you know that every single host you attempt to test is down.

The following utility will do an ICMP Echo check & ensure that the user running the utility has the correct permissions.



import java.net.*;
import com.sun.security.auth.module.UnixSystem;

/**
 *
 * @author Tres Wong-Godfrey
 */
public class IcmpEcho {

    public static void main(String[] args) {
        String host = null;
        int timeOut = 3000;
        boolean isUp = false;
        boolean validRequest = true;
        String output = "";
        long uid = -1;

        UnixSystem user = new UnixSystem();
        uid = user.getUid();

        if (args.length != 1) {
            System.out.println("ICMP echo check requires a single argument -- the hostname");
            System.exit(1);
        }

        if (uid != 0) {
            System.out.println(" ICMP echo check requires root permissions");
            System.exit(2);

        }

        host = args[0];
        try {
            isUp = InetAddress.getByName(host).isReachable(timeOut);
        } catch (SecurityException $e) {
            System.out.println(" ICMP echo check requires root permissions");
            validRequest = false;

        } catch (UnknownHostException $e) {
            System.out.println(" Unknown host: " + host);
            validRequest = false;

        } catch (Exception $e) {
            System.out.println("Unknown error");
            $e.printStackTrace();
            validRequest = false;

        }

        if (validRequest == true) {
            output = (isUp == true) ? host + " is up" : host + " is down";
        }
        System.out.println(output);

    }
}


Posted in ,  | Tags ,

Comments are disabled