1 import java.io.BufferedReader;
2 import java.io.IOException;
3 import java.io.InputStream;
4 import java.io.InputStreamReader;
5
6 /**
7 * 判断网络连接状况.
8 * @author 9 * @date 2019年3月25日
10 */
11 public class PingIpUtil {
12
13 /**
14 * 校验是否可以连通
15 * @param ip
16 * @return true/false
17 */
18 public static boolean isConnect(String ip){
19 boolean connect = false;
20 Runtime runtime = Runtime.getRuntime();
21 Process process;
22 try {
23 process = runtime.exec("ping " + ip);
24 InputStream is = process.getInputStream();
25 InputStreamReader isr = new InputStreamReader(is);
26 BufferedReader br = new BufferedReader(isr);
27 String line = null;
28 StringBuffer sb = new StringBuffer();
29 while ((line = br.readLine()) != null) {
30 sb.append(line);
31 }
32 is.close();
33 isr.close();
34 br.close();
35
36 if (null != sb && !sb.toString().equals("")) {
37 String logString = "";
38 if (sb.toString().indexOf("TTL") > 0) {
39 // 网络畅通
40 connect = true;
41 } else {
42 // 网络不畅通
43 connect = false;
44 }
45 }
46 } catch (IOException e) {
47 e.printStackTrace();
48 }
49 return connect;
50 }
51
52 public static void main(String[] args) {
53 PingIpUtil netState = new PingIpUtil();
54 System.out.println("ping结果:"+netState.isConnect("IP"));
55
56 }
57 }