Friday, September 25, 2009

Java - a ping example with java's InetAddress.isReachable()

import java.net.*;
public class Main {
 
    public static void main(String[] args) {
        try{
            // a note: 
            // This the isReachable method is problematic 
            // If you are in a coorporate environment 
            // then you are probably (unknown to you) 
            // using proxy servers.  Java needs to know 
            // what the proxy server and port is 
            // DhttpProxy.host=yourproxyhost.com -DhttpProxy.port 
            // 
            // All of testing I've done at home works fine. 
            // You need to configure java to utilize your proxy 
 
            // gather the ip address associated with the host 
            InetAddress[] addresses = InetAddress.getAllByName("yahoo.com");
 
            // iterate through the ip address with for-each 
            for (InetAddress addr:addresses) {
 
                // the timeout is in milliseconds 2 seconds here 
                if (addr.isReachable(2000)){
                    System.out.printf("%s is reachable", addr);
                    System.out.println();
                }
                else{
                    System.out.printf("%s is not reachable", addr);
                    System.out.println();
                }
            }
        }
        catch(Exception e) {
            System.out.println("host is unknown (or unresolvable)");
        }
    }
}
/* 
 *      Output (for me): 
        yahoo.com/69.147.114.224 is reachable 
        yahoo.com/209.131.36.159 is reachable 
        yahoo.com/209.191.93.53 is reachable 
*/ 
 

No comments:

Post a Comment