代码实现如下:
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
原文:https://www.cnblogs.com/miracle-luna/p/12026797.html