Advertisement
Guest User

Untitled

a guest
Jan 18th, 2017
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.94 KB | None | 0 0
  1. import java.io.BufferedReader;
  2. import java.io.IOException;
  3. import java.io.InputStreamReader;
  4. import java.net.InetAddress;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7.  
  8. public class Ping {
  9.  
  10. public static boolean ping(String ipAddress) throws Exception {
  11. int timeOut = 3000 ; //超时应该在3钞以上
  12. boolean status = InetAddress.getByName(ipAddress).isReachable(timeOut); // 当返回值是true时,说明host是可用的,false则不可。
  13. return status;
  14. }
  15.  
  16. public static void ping02(String ipAddress) throws Exception {
  17. String line = null;
  18. try {
  19. Process pro = Runtime.getRuntime().exec("ping " + ipAddress);
  20. BufferedReader buf = new BufferedReader(new InputStreamReader(
  21. pro.getInputStream()));
  22. while ((line = buf.readLine()) != null)
  23. System.out.println(line);
  24. } catch (Exception ex) {
  25. System.out.println(ex.getMessage());
  26. }
  27. }
  28.  
  29. public static boolean ping(String ipAddress, int pingTimes, int timeOut) {
  30. BufferedReader in = null;
  31. Runtime r = Runtime.getRuntime(); // 将要执行的ping命令,此命令是windows格式的命令
  32. String pingCommand = "ping " + ipAddress + " -n " + pingTimes + " -w " + timeOut;
  33. try { // 执行命令并获取输出
  34. System.out.println(pingCommand);
  35. Process p = r.exec(pingCommand);
  36. if (p == null) {
  37. return false;
  38. }
  39. in = new BufferedReader(new InputStreamReader(p.getInputStream())); // 逐行检查输出,计算类似出现=23ms TTL=62字样的次数
  40. int connectedCount = 0;
  41. String line = null;
  42. while ((line = in.readLine()) != null) {
  43. connectedCount += getCheckResult(line);
  44. } // 如果出现类似=23ms TTL=62这样的字样,出现的次数=测试次数则返回真
  45. return connectedCount == pingTimes;
  46. } catch (Exception ex) {
  47. ex.printStackTrace(); // 出现异常则返回假
  48. return false;
  49. } finally {
  50. try {
  51. in.close();
  52. } catch (IOException e) {
  53. e.printStackTrace();
  54. }
  55. }
  56. }
  57. //若line含有=18ms TTL=16字样,说明已经ping通,返回1,否则返回0.
  58. private static int getCheckResult(String line) { // System.out.println("控制台输出的结果为:"+line);
  59. Pattern pattern = Pattern.compile("(\\d+ms)(\\s+)(TTL=\\d+)", Pattern.CASE_INSENSITIVE);
  60. Matcher matcher = pattern.matcher(line);
  61. while (matcher.find()) {
  62. return 1;
  63. }
  64. return 0;
  65. }
  66. public static void main(String[] args) throws Exception {
  67. String ipAddress = "172.18.1.171";
  68. System.out.println(ping(ipAddress));
  69. ping02(ipAddress);
  70. System.out.println(ping(ipAddress, 5, 5000));
  71. }
  72. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement