Java Code Examples for java.net.InetAddress#isReachable()

The following examples show how to use java.net.InetAddress#isReachable() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: PingThis.java    From jdk8u60 with GNU General Public License v2.0 7 votes vote down vote up
public static void main(String args[]) throws Exception {
    if (System.getProperty("os.name").startsWith("Windows")) {
        return;
    }

    boolean preferIPv4Stack = "true".equals(System
            .getProperty("java.net.preferIPv4Stack"));
    List<String> addrs = new ArrayList<String>();
    InetAddress inetAddress = null;

    addrs.add("0.0.0.0");
    if (!preferIPv4Stack) {
        if (hasIPv6()) {
            addrs.add("::0");
        }
    }

    for (String addr : addrs) {
        inetAddress = InetAddress.getByName(addr);
        System.out.println("The target ip is "
                + inetAddress.getHostAddress());
        boolean isReachable = inetAddress.isReachable(3000);
        System.out.println("the target is reachable: " + isReachable);
        if (isReachable) {
            System.out.println("Test passed ");
        } else {
            System.out.println("Test failed ");
            throw new Exception("address " + inetAddress.getHostAddress()
                    + " can not be reachable!");
        }
    }
}
 
Example 2
Source File: VisorTaskUtils.java    From ignite with Apache License 2.0 6 votes vote down vote up
/**
 * Checks if address can be reached using one argument InetAddress.isReachable() version or ping command if failed.
 *
 * @param addr Address to check.
 * @param reachTimeout Timeout for the check.
 * @return {@code True} if address is reachable.
 */
public static boolean reachableByPing(InetAddress addr, int reachTimeout) {
    try {
        if (addr.isReachable(reachTimeout))
            return true;

        String cmd = String.format("ping -%s 1 %s", U.isWindows() ? "n" : "c", addr.getHostAddress());

        Process myProc = Runtime.getRuntime().exec(cmd);

        myProc.waitFor();

        return myProc.exitValue() == 0;
    }
    catch (IOException ignore) {
        return false;
    }
    catch (InterruptedException ignored) {
        Thread.currentThread().interrupt();

        return false;
    }
}
 
Example 3
Source File: GooglePingStatusChecker.java    From appstatus with Apache License 2.0 6 votes vote down vote up
public ICheckResult checkStatus() {
	ICheckResult result = null;

	try {
		InetAddress address = InetAddress.getByName("www.google.com");

		if (address.isReachable(2000)) {
			result = createResult(OK);
			result.setDescription("Google Access ok");

		} else {
			throw new Exception("Ping timeout (2000ms)");
		}

	} catch (Exception e) {
		result = createResult(WARN);
		result.setDescription("Google ping failed");
		result.setResolutionSteps("Ping failed. This means that ICMP messages are blocked by this host. (This may not be an issue) "
				+ e.getMessage());

	}

	return result;
}
 
Example 4
Source File: PingWatchdogService.java    From mokka7 with Eclipse Public License 1.0 6 votes vote down vote up
private boolean isReachable(InetAddress address, int timeOutMillis) throws Exception {
	if (isWindowsOS) {
		return address.isReachable(timeOutMillis);
	}
	Process p = new ProcessBuilder("ping", "-c", "1", address.getHostAddress()).start();
	try {
		p.waitFor(timeOutMillis, TimeUnit.MILLISECONDS);
	} catch (InterruptedException e) {
		return false;
	}
	if (p.isAlive()){
		return false;
	}
	int exitValue = p.exitValue();
	logger.trace("exit value: {}", exitValue);

	return exitValue == 0;
}
 
Example 5
Source File: ClientApplication.java    From ClusterDeviceControlPlatform with MIT License 6 votes vote down vote up
public static void main(String[] args) {
    try {
        if (args.length > 0) {
            String ip = args[0];
            InetAddress inetAddress = InetAddress.getByName(ip);
            if (!inetAddress.isReachable(CommSetting.ACCESSIBLE_CHANNEL_REPLY_INTERVAL)) {
                System.out.println("输入的第一个参数有误");
                return;
            }

            CommSetting.SERVER_HOSTNAME = ip;
        }

        if (args.length > 1) {
            DeviceSetting.MAX_GROUP_ID = Integer.parseInt(args[1]);
        }
    } catch (IOException var3) {
        System.out.println("指定的服务器连接超时!");
        return;
    } catch (NumberFormatException var4) {
        System.out.println("输入的第二个参数有误,请检查!");
    }

    System.out.println("服务器地址: " + CommSetting.SERVER_HOSTNAME + ", 最大设备组数量: " + DeviceSetting.MAX_GROUP_ID);
    SpringApplication.run(ClientApplication.class, args);
}
 
Example 6
Source File: InetAddressHealthCheck.java    From smallrye-health with Apache License 2.0 6 votes vote down vote up
@Override
public HealthCheckResponse call() {
    final HealthCheckResponseBuilder healthCheckResponseBuilder = HealthCheckResponse.named(this.name);
    healthCheckResponseBuilder.withData("host", this.host);
    try {
        InetAddress addr = InetAddress.getByName(this.host);
        final boolean reachable = addr.isReachable(this.timeout);
        if (!reachable) {
            healthCheckResponseBuilder.withData("error", String.format("Host %s not reachable.", this.host));
        }

        healthCheckResponseBuilder.state(reachable);
    } catch (IOException e) {
        HealthChecksLogging.log.inetAddressHealthCheckError(e);

        healthCheckResponseBuilder.withData("error", e.getMessage());
        healthCheckResponseBuilder.down();
    }

    return healthCheckResponseBuilder.build();
}
 
Example 7
Source File: JobEntryPing.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
private boolean systemPing( String hostname, int timeout ) {
  boolean retval = false;

  InetAddress address = null;
  try {
    address = InetAddress.getByName( hostname );
    if ( address == null ) {
      logError( BaseMessages.getString( PKG, "JobPing.CanNotGetAddress", hostname ) );
      return retval;
    }

    if ( log.isDetailed() ) {
      logDetailed( BaseMessages.getString( PKG, "JobPing.HostName", address.getHostName() ) );
      logDetailed( BaseMessages.getString( PKG, "JobPing.HostAddress", address.getHostAddress() ) );
    }

    retval = address.isReachable( timeout );
  } catch ( Exception e ) {
    logError( BaseMessages.getString( PKG, "JobPing.ErrorSystemPing", hostname, e.getMessage() ) );
  }
  return retval;
}
 
Example 8
Source File: IsReachable.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        InetAddress addr = InetAddress.getByName("localhost");
        if (!addr.isReachable(10000))
            throw new RuntimeException("Localhost should always be reachable");
        NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
        if (inf != null) {
            if (!addr.isReachable(inf, 20, 10000))
            throw new RuntimeException("Localhost should always be reachable");
        }

    } catch (IOException e) {
        throw new RuntimeException("Unexpected exception:" + e);
    }
}
 
Example 9
Source File: PingThis.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    if (System.getProperty("os.name").startsWith("Windows")) {
        return;
    }

    boolean preferIPv4Stack = "true".equals(System
            .getProperty("java.net.preferIPv4Stack"));
    List<String> addrs = new ArrayList<String>();
    InetAddress inetAddress = null;

    addrs.add("0.0.0.0");
    if (!preferIPv4Stack) {
        if (hasIPv6()) {
            addrs.add("::0");
        }
    }

    for (String addr : addrs) {
        inetAddress = InetAddress.getByName(addr);
        System.out.println("The target ip is "
                + inetAddress.getHostAddress());
        boolean isReachable = inetAddress.isReachable(3000);
        System.out.println("the target is reachable: " + isReachable);
        if (isReachable) {
            System.out.println("Test passed ");
        } else {
            System.out.println("Test failed ");
            throw new Exception("address " + inetAddress.getHostAddress()
                    + " can not be reachable!");
        }
    }
}
 
Example 10
Source File: IsReachable.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        InetAddress addr = InetAddress.getByName("localhost");
        if (!addr.isReachable(10000))
            throw new RuntimeException("Localhost should always be reachable");
        NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
        if (inf != null) {
            if (!addr.isReachable(inf, 20, 10000))
            throw new RuntimeException("Localhost should always be reachable");
        }

    } catch (IOException e) {
        throw new RuntimeException("Unexpected exception:" + e);
    }
}
 
Example 11
Source File: NetUtils.java    From kafka-eagle with Apache License 2.0 5 votes vote down vote up
/** Ping server whether alive. */
public static boolean ping(String host) {
	try {
		InetAddress address = InetAddress.getByName(host);
		return address.isReachable(ServerDevice.TIME_OUT);
	} catch (Exception e) {
		LOG.error("Ping [" + host + "] server has crash or not exist.");
		return false;
	}
}
 
Example 12
Source File: IsReachable.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        InetAddress addr = InetAddress.getByName("localhost");
        if (!addr.isReachable(10000))
            throw new RuntimeException("Localhost should always be reachable");
        NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
        if (inf != null) {
            if (!addr.isReachable(inf, 20, 10000))
            throw new RuntimeException("Localhost should always be reachable");
        }

    } catch (IOException e) {
        throw new RuntimeException("Unexpected exception:" + e);
    }
}
 
Example 13
Source File: IsReachable.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        InetAddress addr = InetAddress.getByName("localhost");
        if (!addr.isReachable(10000))
            throw new RuntimeException("Localhost should always be reachable");
        NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
        if (inf != null) {
            if (!addr.isReachable(inf, 20, 10000))
            throw new RuntimeException("Localhost should always be reachable");
        }

    } catch (IOException e) {
        throw new RuntimeException("Unexpected exception:" + e);
    }
}
 
Example 14
Source File: PingThis.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    if (System.getProperty("os.name").startsWith("Windows")) {
        return;
    }

    boolean preferIPv4Stack = "true".equals(System
            .getProperty("java.net.preferIPv4Stack"));
    List<String> addrs = new ArrayList<String>();
    InetAddress inetAddress = null;

    addrs.add("0.0.0.0");
    if (!preferIPv4Stack) {
        if (hasIPv6()) {
            addrs.add("::0");
        }
    }

    for (String addr : addrs) {
        inetAddress = InetAddress.getByName(addr);
        System.out.println("The target ip is "
                + inetAddress.getHostAddress());
        boolean isReachable = inetAddress.isReachable(3000);
        System.out.println("the target is reachable: " + isReachable);
        if (isReachable) {
            System.out.println("Test passed ");
        } else {
            System.out.println("Test failed ");
            throw new Exception("address " + inetAddress.getHostAddress()
                    + " can not be reachable!");
        }
    }
}
 
Example 15
Source File: IsReachable.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        InetAddress addr = InetAddress.getByName("localhost");
        if (!addr.isReachable(10000))
            throw new RuntimeException("Localhost should always be reachable");
        NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
        if (inf != null) {
            if (!addr.isReachable(inf, 20, 10000))
            throw new RuntimeException("Localhost should always be reachable");
        }

    } catch (IOException e) {
        throw new RuntimeException("Unexpected exception:" + e);
    }
}
 
Example 16
Source File: IsReachable.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {
        InetAddress addr = InetAddress.getByName("localhost");
        if (!addr.isReachable(10000))
            throw new RuntimeException("Localhost should always be reachable");
        NetworkInterface inf = NetworkInterface.getByInetAddress(addr);
        if (inf != null) {
            if (!addr.isReachable(inf, 20, 10000))
            throw new RuntimeException("Localhost should always be reachable");
        }

    } catch (IOException e) {
        throw new RuntimeException("Unexpected exception:" + e);
    }
}
 
Example 17
Source File: PingThis.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public static void main(String args[]) throws Exception {
    if (System.getProperty("os.name").startsWith("Windows")) {
        return;
    }

    boolean preferIPv4Stack = "true".equals(System
            .getProperty("java.net.preferIPv4Stack"));
    List<String> addrs = new ArrayList<String>();
    InetAddress inetAddress = null;

    addrs.add("0.0.0.0");
    if (!preferIPv4Stack) {
        if (hasIPv6()) {
            addrs.add("::0");
        }
    }

    for (String addr : addrs) {
        inetAddress = InetAddress.getByName(addr);
        System.out.println("The target ip is "
                + inetAddress.getHostAddress());
        boolean isReachable = inetAddress.isReachable(3000);
        System.out.println("the target is reachable: " + isReachable);
        if (isReachable) {
            System.out.println("Test passed ");
        } else {
            System.out.println("Test failed ");
            throw new Exception("address " + inetAddress.getHostAddress()
                    + " can not be reachable!");
        }
    }
}
 
Example 18
Source File: HttpConnector.java    From TeamcityTriggerHook with GNU Lesser General Public License v3.0 5 votes vote down vote up
public boolean isReachable(TeamcityConfiguration conf, Settings settings) {
    try {       
        InetAddress address = InetAddress.getByName(conf.getUrl().replace("http://", "").replace("https://", ""));
        address.isReachable(500);
        return true;
    } catch (IOException e) {
        TeamcityLogger.logMessage(settings, "[HttpConnector][isReachable] Failed to reach server, skip queue checker thread to avoid deadlocks: " + e.getMessage());
        return false;
    }
}
 
Example 19
Source File: StreamingV2Service.java    From kylin with Apache License 2.0 5 votes vote down vote up
private boolean isReceiverReachable(Node receiver) {
    try {
        InetAddress address = InetAddress.getByName(receiver.getHost());//ping this IP
        boolean reachable = address.isReachable(1000);
        if (!reachable) {
            return false;
        }
        return true;
    } catch (Exception exception) {
        logger.error("exception when try ping host:" + receiver.getHost(), exception);
        return false;
    }
}
 
Example 20
Source File: NetworkUtil.java    From TvLauncher with Apache License 2.0 5 votes vote down vote up
public static boolean isReachable(String ipOrHost) {
    try {
        InetAddress address = InetAddress.getByName(ipOrHost);
        return address.isReachable(5000);
    } catch (IOException e) {
        System.err.println("Unable to reach " + ipOrHost);
    }
    return false;
}