java中检测网络是否相通

转载:https://www.cnblogs.com/moon-jiajun/p/3454576.html

 

复制代码
 1 package com.cjj.client;
 2 
 3 import java.io.IOException;
 4 import java.io.InputStream;
 5 import java.net.InetAddress;
 6 import java.net.URL;
 7 
 8 public class InetJavaTest {
 9     private static String remoteInetAddr = "59.231.36.59";//需要连接的IP地址
10      /**
11      * 传入需要连接的IP,返回是否连接成功
12      * @param remoteInetAddr
13      * @return
14      */
15     public static boolean isReachable(String remoteInetAddr) {
16         boolean reachable = false; 
17         try {   
18             InetAddress address = InetAddress.getByName(remoteInetAddr); 
19             reachable = address.isReachable(5000);  
20             } catch (Exception e) {  
21             e.printStackTrace();  
22             }  
23         return reachable;
24     }
25     
26     public static void main(String[] args) {
27         URL url = null;
28         Boolean bon = false;
29         try {
30         url = new URL("http://baicu.com/");
31         InputStream in = url.openStream();//打开到此 URL 的连接并返回一个用于从该连接读入的 InputStream
32         System.out.println("连接正常");
33         in.close();//关闭此输入流并释放与该流关联的所有系统资源。
34         } catch (IOException e) {
35         System.out.println("无法连接到:" + url.toString());
36         }
37         bon = isReachable(remoteInetAddr);
38         System.out.println("pingIP:" + bon);
39     }
40 }
复制代码

 

posted @ 2018-08-31 14:49  ConfidentLiu  阅读(936)  评论(0编辑  收藏  举报