方案一:ping
boolean connect = false;
Runtime runtime = Runtime.getRuntime();
Process process;
try {
process = runtime.exec("ping " + ipPath);
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is,"GBK");
BufferedReader br = new BufferedReader(isr);
String line = null;
StringBuffer sb = new StringBuffer();
while ((line = br.readLine()) != null) {
sb.append(line);
}
System.out.println("返回值为:"+sb);
is.close();
isr.close();
br.close();
if (null != sb && !sb.toString().equals("")) {
String logString = "";
if (sb.toString().indexOf("TTL") > 0) {
// OK
connect = true;
} else {
// NO OK
connect = false;
}
}
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(connect);
方案二:
boolean reachable = InetAddress.getByName("202.108.22.6")
.isReachable(3000);//3s连不上
System.out.println(reachable);//true:能连/反之不能