## ping 命令 在 java 中的使用

在 平时 访问 一个 网址的是否,出现 请求异常, 通常 会 用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;
    }

参考:

Java实现ping功能的三种方法

原文地址:https://www.cnblogs.com/idea-persistence/p/13564594.html