Wednesday 15 February 2012

Native OS ping implemented in Java

I've recently had to implement this very handy code to do an operating system dependent native ping. You'll notice I've created an OSType Enumerator type to represent the OS in question. Also, I've implemented two classes to represent the host to be "ping-ed" as well as the ping result. See below...


   private Process constructWindowsOSProcess(Runtime rt, PingHost host)
                throws IOException {
        return rt.exec("ping -n 1 -w "+ host.getTimeout() +" "+host.getNameOrIP());
    }
   
    private Process constructLinuxOSProcess(Runtime rt, PingHost host)

                throws IOException {
        return rt.exec("ping -c 1 -W "+ (host.getTimeout()/1000) +" "+host.getNameOrIP());
    }
   
    private Process constructOSSpecificProcess(Runtime rt, OSType osType,

             PingHost host) throws IOException {
        if (OSType.WINDOWS == osType) {
            return constructWindowsOSProcess(rt, host);
        } else if (OSType.LINUX == osType) {
            return constructLinuxOSProcess(rt, host);
        }
        return constructWindowsOSProcess(rt, host);
    }


    private boolean isReachable(OSType osType, String pingResult) {
        if ((OSType.WINDOWS == osType) && (-1 < pingResult.indexOf(":Reply"))) {
            return true;
        } else if ((OSType.LINUX == osType) && (-1 < pingResult.indexOf("64 bytes from"))) {
            return true;
        }
        return false;
    } 


   /**
     * Pings a host natively with the specified milliseconds(contained in PingHost)

     * as time-out for the ping.
     * @param rt Java Runtime to use in this method
     * @param osType the OS type this code is executing on or should be based on

                              (enum class type)
     * @param host encapsulation of a pingable host and all its attributes.
     * @return PingResult indicating whether the host is reachable or not.
     */
    private PingResult doNativeOSPing(Runtime rt, OSType osType, PingHost host) {
        StringBuffer pingResult = new StringBuffer("");
        try {                       
            Process p = this.constructOSSpecificProcess(rt, osType, host);           
            BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null) {
                pingResult.append(inputLine);
            }
            in.close();
           
        } catch (IOException e) {           
            e.printStackTrace();
        }
        return new PingResult(host, this.isReachable(osType, pingResult.toString()));
    }

No comments:

Post a Comment