Root Permissions Required to Send ICMP Echo Request From Java using java.net.InetAddress

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 ,

No finally in PHP Exceptions

Posted by Tres Sat, 19 Apr 2008 14:12:00 GMT

PHP’s implementation of Exceptions works just like you’d expect it to, except for the missing finally statement.

In Java, we could do something like this:

        try {
            //create a new widget
            Widget widget = new Widget();
            //here's where we lock the widget before we take action
            widget.lock();
            widget.doStuf();
        } catch( TimeoutException e ) {
            widget.fixTimeoutException();
        } catch( ConnectionException e ) {
            widget.resetConnection();
        } catch( PermissionException e ) {
            widget.exit();
        } catch( FantasticException e ) {
            widget.goBallistic();
        } finally {
            //make sure that we're unlocking the widget since we put a lock on it before
            widget.unlock();
        } 

But when describing the same thing in PHP, we’ve got to do it like this because there’s no finally available:

try{
    //create a new widget
    $widget = new Widget();
    //here's where we lock the widget before we take action
    $widget->lock();
    $widget->doStuff();
} catch( TimeoutException $e ) {
    $widget->fixTimeoutException();
    //make sure that we're unlocking the widget since we put a lock on it before
    $widget->unlock();
} catch( ConnectionException $e ) {
    $widget->resetConnection();
    //make sure that we're unlocking the widget since we put a lock on it before
    $widget->unlock();
} catch( PermissionException $e ) {
    $widget->exit();
    //make sure that we're unlocking the widget since we put a lock on it before
    $widget->unlock();
} catch( FantasticException $e ) {
    $widget->goBallistic();
    //make sure that we're unlocking the widget since we put a lock on it before
    $widget->unlock();
}

It’s great to have exceptions in PHP, don’t get me wrong, it just took me by surprise that the implementation wasn’t complete.

Posted in , ,  | Tags , , ,

Using PHP __autoload() For Better OOP Class Management

Posted by Tres Sat, 19 Apr 2008 08:42:00 GMT

Keeping your classes well organized is an extremely important process once you reach the point where you’re dealing with hundreds of classes and thousands of lines of code. One of the ways that Java implicitly facilitates better organization is by forcing classes into their own files.

Unlike Java, where strict conventions make loading of called classes automatic, with PHP, you can put your classes anywhere, just as long as they’re in a file that the interpreter knows about via an include or require.

This kind of organization is just fine if you’re working on a smaller code base, but quickly breaks down when you’re dealing with a larger project; however,PHP does offer the built-in function __autoload() which automatically attempts to load any class or interface which hasn’t been defined yet. So you can take advantage of single-class files without needing to include (potentially) hundreds of files.

The only thing is, you’ve got to put together the _autoload yourself. Here’s the implementation of _autoload() that I’m currently using. It will load classes, interfaces and configuration files. It uses setincludepath() to define where it should be looking for files.


/**
 * 
 *  
 *
 * @copyright 2008
 * @package ProjectX
 * @subpackage SystemConf
 * @author Tres Wong-Godfrey
 * 
 */


define( "LIBRARY", "/usr/local/emersius/projectx/library/" );

define( "COMMON_LIBRARY", "/usr/local/emersius/common/" );

define( "CONF_DIR", "/usr/local/emersius/conf/" );


/**
 * 
 * Object autoloader for projectX
 * 
 * @access public
 * @param string The name of the class being loaded
 *
 */
function __autoload($class)
{
    //turn down the volume of error reporting while we're running the autoloader so we don't get warnings from the include_once() calls.
    $old_error_reporting_level = error_reporting( 1 );
    try {
        switch( TRUE ) {
            case include_once("class.${class}.php"):
            return;

            case include_once("intf.${class}.php"):
            return;

            case include_once( "conf.${class}.php" ):
            return;

            default:
            throw new FileNotFoundException(__CLASS__.'::'.__FUNCTION__ . "Fault occured in ".__FUNCTION__. "can not find incldued library ${class}.\n");

        }
    } catch( FileNotFoundException $e ) {
        die( $e->getMessage() . "\n" . $e->getTraceAsString() );
    }

    //turn the error reporting back up to what it was
    error_reporting( $old_error_reporting_level );


}

/**
 * Sets the path where we will look for files when they
 * are requested.
 */
set_include_path(
        get_include_path()
        .PATH_SEPARATOR.LIBRARY
        .PATH_SEPARATOR.CONF_DIR
        .PATH_SEPARATOR.COMMON_LIBRARY
        .PATH_SEPARATOR.COMMON_LIBRARY."/classes/"
        .PATH_SEPARATOR.COMMON_LIBRARY."/classes/logging/"
        .PATH_SEPARATOR.COMMON_LIBRARY."/classes/exceptions/"
        .PATH_SEPARATOR.COMMON_LIBRARY."/classes/models/"
        .PATH_SEPARATOR.COMMON_LIBRARY."/interfces/"
);

Posted in , ,  | Tags , , , , ,

Recursively Counting Lines of Code for An Entire Project Folder

Posted by Tres Wed, 09 Apr 2008 20:50:00 GMT

Here’s a little bash shell foo to figure out how many lines of code are in a specific directory and all its subdirectories.

As written, it looks for java files and excludes blank lines as well as subversion management directories:

totalcount=0
for i in `find . -name "*.java" -print | grep -v ".svn"`
do newcount=`cat $i | grep -v "^$" | wc -l`
totalcount=$(($totalcount+$newcount))
done
echo "totalcount: $totalcount"

Posted in , , ,  | Tags , ,