亲宝软件园·资讯

展开

Java判断主机是否能ping通代码实例

人气:0

这篇文章主要介绍了Java判断主机是否能ping通代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

代码实现如下:

import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * Created by Miracle Luna on 2019/12/10
 */
public class PingUtil {
  public static void main(String[] args) {
    String host1 = "14.215.178.37";
    String host2 = "www.baidu.com";
    ping(host1);
    ping(host2);
  }

  /**
   * 判断主机地址能不能 ping 通,此处主机地址可以域名或者IP
   * @param host
   * @return
   */
  public static void ping(String host) {
    try {
      InetAddress inetAddress = InetAddress.getByName(host);
      boolean reachable = inetAddress.isReachable(5*1000);
      if(reachable) {
        System.out.println("ping success. Host name: " + inetAddress.getHostName() + ", IP addr: " + inetAddress.getHostAddress());
      }else {
        System.out.println("ping failed.");
      }
    } catch (UnknownHostException e1) {
      e1.printStackTrace();
    } catch (IOException e2) {
      e2.printStackTrace();
    }
  }
}

运行结果如下:

ping success. Host name: 14.215.178.37, IP addr: 14.215.178.37
ping success. Host name: www.baidu.com, IP addr: 14.215.177.39

您可能感兴趣的文章:

加载全部内容

相关教程
猜你喜欢
用户评论