-
九21
Java模拟ping的程序
Posted in 技术·学习, -
可以用于检测某个ip地址是否可以ping通,网上找的,可以直接运行.
package com.demo; import java.io.*; public class ping { public static void main(String [] args) { System.out.println(pingServer("localhost",100)); } /** * ping the server * @param server String * @param timeout int * @return boolean * @throws IOException */ public static boolean pingServer(String server,int timeout) { BufferedReader in = null; Runtime r = Runtime.getRuntime(); String pingCommand = "ping " + server + " -n 1 -w " + timeout; try { Process p = r.exec(pingCommand); if (p == null) { return false; } in = new BufferedReader(new InputStreamReader(p.getInputStream())); String line = null; while ( (line = in.readLine()) != null) { if (line.startsWith("Reply from")) { return true; } System.out.println(line); } in.close(); } catch (Exception ex) { ex.printStackTrace(); return false; } return false; } };