package com.its.api.utils;

import java.io.IOException;
import java.net.InetAddress;

public class Ping {
    public static boolean isReachable(String host, int timeoutSec) throws IOException, InterruptedException {

        if (OS.isWindows())
            return Ping.winPing(host);

        return Ping.unixPing(host, timeoutSec);
    }

    private static boolean winPing(String host) throws IOException, InterruptedException {
        String cmd = "cmd /c ping -n 1 " + host + " | find \"TTL\"";
        Process proc = Runtime.getRuntime().exec(cmd);
        int exit = proc.waitFor();
        return (exit == 0) ? true : false;
    }

    private static boolean unixPing(String host, int timeoutSec) throws IOException {
        InetAddress targetIp = InetAddress.getByName(host);
        return targetIp.isReachable(timeoutSec*1000);
    }
}
