## ping 命令 在 java 中的使用
阿新 • • 發佈:2020-08-26
在 平時 訪問 一個 網址的是否,出現 請求異常, 通常 會 用ping ip
的方式 檢視 ip 或者域名是否 能通;通的話,進一步檢視 telnet ip port
檢視埠是否 可通的 方式進行排查。 如果對 路由做了設定,可以用 tracerout ip
的方式 檢視路徑是否合理。
背景
這次在專案中,在 專案中 涉及到 ip 在 交換機是否 配置成功的判斷時, 經過向bmc 同學的諮詢。參考 用ping ip的方式 判斷。 網上查詢到 java ping ip 的實現
方式很多。主要是以下四種(讓我看來 3和4 類似)
-
1、用 Jdk1.5的InetAddresss方式
-
public static boolean ping(String ipAddress) throws Exception { int timeOut = 3000 ; //超時應該在3鈔以上 boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut); // 當返回值是true時,說明host是可用的,false則不可。 return status; }
-
使用時應注意,如果遠端伺服器設定了防火牆或相關的配製,可能會影響到結果。另外,由於傳送ICMP請求需要程式對系統有一定的許可權,當這個許可權無法滿足時, isReachable方法將試著連線遠端主機的TCP埠 7(Echo)
-
-
2、模擬TELNET,利用Socket的connect(SocketAddress endpoint, inttimeout)方法可以實現telnet的功能
-
static void socketTest(String ip,int port,int timeOut){ try { Socket server = new Socket(); InetSocketAddress address = new InetSocketAddress(ip,port); server.connect(address, timeOut); System.out.println(server.isConnected()); server.close(); } catch (UnknownHostException e){ System.out.println("telnet失敗"); } catch (IOException e){ System.out.println("telnet失敗"); }
-
-
3、直接用Runtime 使用 cmd 直接 ping ip
-
public static void ping(String ipAddress) throws Exception { String line = null; try { Process pro = Runtime.getRuntime().exec("ping " + ipAddress); BufferedReader buf = new BufferedReader(new InputStreamReader( pro.getInputStream())); while ((line = buf.readLine()) != null) System.out.println(line); } catch (Exception ex) { System.out.println(ex.getMessage()); } }
-
-
4、Java呼叫控制檯執行ping
- 通過 使用ping 的引數 來進行判斷
針對不通的作業系統, ping的引數 略有不同,針對網上的參考參考1 。
public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
BufferedReader in = null;
String pingCommand;
Runtime r = Runtime.getRuntime();
String osName = System.getProperty("os.name");
if(osName.contains("Windows")){
pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
}else if(osName.contains("Mac")){
pingCommand = "ping " + " -c " + "4" + " -t " + "2 " + ipAddress;
}else{//linux
pingCommand = "ping " + " -c " + "4" + " -w " + "2 " + ipAddress;
}
try {
Process p = r.exec(pingCommand);
if (p == null) {
return false;
}
in = new BufferedReader(new InputStreamReader(p.getInputStream()));
int connectedCount = 0;
String line;
while ((line = in.readLine()) != null) {
connectedCount += getCheckResult(line,osName);
}
return connectedCount >= 2 ? true : false;
} catch (Exception ex) {
ex.printStackTrace(); //出現異常則返回假
return false;
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static int getCheckResult(String line,String osName) {
if(osName.contains("Windows")){
if(line.contains("TTL=")){
return 1;
}
}else{
if(line.contains("ttl=")){
return 1;
}
}
return 0;
}