首页 > 编程语言 > 详细

Java 实现判断 主机是否能 ping 通

时间:2019-12-12 09:06:21      阅读:178      评论:0      收藏:0      [点我收藏+]

代码实现如下:

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

/**
 * Created by Miracle Luna on 2019/12/10
 */
public class PingHost {
    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

技术分享图片

Java 实现判断 主机是否能 ping 通

原文:https://www.cnblogs.com/miracle-luna/p/12026797.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!