一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - java如何測試網絡連通性

java如何測試網絡連通性

2020-06-27 13:01服務器之家 JAVA教程

這篇文章主要為大家詳細介紹了java測試網絡連通性的兩種方式,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了Java測試網絡連通性的方法,供大家參考,具體內容如下

第一種方式:利用java運行時:
Java代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/**
 * test network
 * @param ip
 */
private void getNetworkState(String ip) {
  Runtime runtime = Runtime.getRuntime();
  try {
    log.info("=================正在測試網絡連通性ip:"+ip);
    Process process = runtime.exec("ping " +ip);
    InputStream iStream = process.getInputStream();
    InputStreamReader iSReader = new InputStreamReader(iStream,"UTF-8");
    BufferedReader bReader = new BufferedReader(iSReader);
    String line = null;
    StringBuffer sb = new StringBuffer();
    while ((line = bReader.readLine()) != null) {
      sb.append(line);
    }
    iStream.close();
    iSReader.close();
    bReader.close();
    String result = new String(sb.toString().getBytes("UTF-8"));
    log.info("ping result:"+result);
    if (!StringUtils.isBlank(result)) {
      if (result.indexOf("TTL") > 0 || result.indexOf("ttl") > 0) {
        log.info("網絡正常,時間: " + TimeUtil.getCurDate("yyyy-mm-dd hh:mm:ss"));    
      } else {
        log.info("網絡斷開,時間 :" + TimeUtil.getCurDate("yyyy-mm-dd hh:mm:ss"));
 
      }
    }
  } catch (Exception e) {
    log.error("網絡異常:"+e.getMessage());
    e.printStackTrace();
  }
}

在windows平臺上,上面代碼沒有為,ping ip 會結束,而在linux環境中ping命令,ping不通時,
會卡住,ping通,會不定的輸出信息,考慮用另一種方式socket。

第二種方式socket:
Java代碼

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
package com.util.network;
 
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
 
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
 
/**
 * 測試網絡連通性
 *
 * @author donald
 *
 */
public class NetworkHelper {
  private static Logger log = LoggerFactory.getLogger(NetworkHelper.class);
  private static NetworkHelper instance = null;
  public static synchronized NetworkHelper getInstance(){
    if(instance == null){
      instance = new NetworkHelper();
    }
    return instance;
 
  }
 
  /**
   * 測試本地能否ping ip
   *
   * @param ip
   * @return
   */
  public boolean isReachIp(String ip) {
    boolean isReach = false;
    try {
      InetAddress address = InetAddress.getByName(ip);// ping this IP
 
      if (address instanceof java.net.Inet4Address) {
        log.info(ip + " is ipv4 address");
      } else if (address instanceof java.net.Inet6Address) {
        log.info(ip + " is ipv6 address");
      } else {
        log.info(ip + " is unrecongized");
      }
      if (address.isReachable(5000)) {
        isReach = true;
        log.info("SUCCESS - ping " + ip
            + " with no interface specified");
      } else {
        isReach = false;
        log.info("FAILURE - ping " + ip
            + " with no interface specified");
      }
    } catch (Exception e) {
      log.error("error occurs:" + e.getMessage());
    }
    return isReach;
  }
 
  /**
   * 測試本地所有的網卡地址都能ping通 ip
   *
   * @param ip
   * @return
   */
  public boolean isReachNetworkInterfaces(String ip) {
    boolean isReach = false;
    try {
      InetAddress address = InetAddress.getByName(ip);// ping this IP
 
      if (address instanceof java.net.Inet4Address) {
        log.info(ip + " is ipv4 address");
      } else if (address instanceof java.net.Inet6Address) {
        log.info(ip + " is ipv6 address");
      } else {
        log.info(ip + " is unrecongized");
      }
      if (address.isReachable(5000)) {
        isReach = true;
        log.info("SUCCESS - ping " + ip
            + " with no interface specified");
      } else {
        isReach = false;
        log.info("FAILURE - ping " + ip
            + " with no interface specified");
      }
      if (isReach) {
        log.info("-------Trying different interfaces--------");
        Enumeration<NetworkInterface> netInterfaces = NetworkInterface
            .getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {
          NetworkInterface ni = netInterfaces.nextElement();
          log.info("Checking interface, DisplayName:"
              + ni.getDisplayName() + ", Name:" + ni.getName());
          if (address.isReachable(ni, 0, 5000)) {
            isReach = true;
            log.info("SUCCESS - ping " + ip);
          } else {
            isReach = false;
            log.info("FAILURE - ping " + ip);
          }
          Enumeration<InetAddress> ips = ni.getInetAddresses();
          while (ips.hasMoreElements()) {
            log.info("IP: " + ips.nextElement().getHostAddress());
          }
          log.info("-----------------check now NetworkInterface is done--------------------------");
        }
      }
    } catch (Exception e) {
      log.error("error occurs:" + e.getMessage());
    }
    return isReach;
  }
 
  /**
   * 獲取能與遠程主機指定端口建立連接的本機ip地址
   * @param remoteAddr
   * @param port
   * @return
   */
  public String getReachableIP(InetAddress remoteAddr, int port) {
    String retIP = null;
    Enumeration<NetworkInterface> netInterfaces;
    try {
      netInterfaces = NetworkInterface.getNetworkInterfaces();
      while (netInterfaces.hasMoreElements()) {
        NetworkInterface ni = netInterfaces.nextElement();
        Enumeration<InetAddress> localAddrs = ni.getInetAddresses();
        while (localAddrs.hasMoreElements()) {
          InetAddress localAddr = localAddrs.nextElement();
          if (isReachable(localAddr, remoteAddr, port, 5000)) {
            retIP = localAddr.getHostAddress();
            break;
          }
        }
      }
    } catch (SocketException e) {
      log.error("Error occurred while listing all the local network addresses:"
          + e.getMessage());
    }
    if (retIP == null) {
      log.info("NULL reachable local IP is found!");
    } else {
      log.info("Reachable local IP is found, it is " + retIP);
    }
    return retIP;
  }
  /**
   * 獲取能與遠程主機指定端口建立連接的本機ip地址
   * @param remoteIp
   * @param port
   * @return
   */
  public String getReachableIP(String remoteIp, int port) {
 
    String retIP = null;
    InetAddress remoteAddr = null;
    Enumeration<NetworkInterface> netInterfaces;
    try {
      remoteAddr = InetAddress.getByName(remoteIp);
      netInterfaces = NetworkInterface.getNetworkInterfaces();
      while (netInterfaces.hasMoreElements()) {
        NetworkInterface ni = netInterfaces.nextElement();
        Enumeration<InetAddress> localAddrs = ni.getInetAddresses();
        while (localAddrs.hasMoreElements()) {
          InetAddress localAddr = localAddrs.nextElement();
          if (isReachable(localAddr, remoteAddr, port, 5000)) {
            retIP = localAddr.getHostAddress();
            break;
          }
        }
      }
    } catch (UnknownHostException e) {
      log.error("Error occurred while listing all the local network addresses:"+ e.getMessage());
    }catch (SocketException e) {
      log.error("Error occurred while listing all the local network addresses:"+ e.getMessage());
    }
    if (retIP == null) {
      log.info("NULL reachable local IP is found!");
    } else {
      log.info("Reachable local IP is found, it is " + retIP);
    }
    return retIP;
  }
  /**
   * 測試localInetAddr能否與遠程的主機指定端口建立連接相連
   *
   * @param localInetAddr
   * @param remoteInetAddr
   * @param port
   * @param timeout
   * @return
   */
  public boolean isReachable(InetAddress localInetAddr,
      InetAddress remoteInetAddr, int port, int timeout) {
    boolean isReachable = false;
    Socket socket = null;
    try {
      socket = new Socket();
      // 端口號設置為 0 表示在本地挑選一個可用端口進行連接
      SocketAddress localSocketAddr = new InetSocketAddress(
          localInetAddr, 0);
      socket.bind(localSocketAddr);
      InetSocketAddress endpointSocketAddr = new InetSocketAddress(
          remoteInetAddr, port);
      socket.connect(endpointSocketAddr, timeout);
      log.info("SUCCESS - connection established! Local: "
          + localInetAddr.getHostAddress() + " remote: "
          + remoteInetAddr.getHostAddress() + " port" + port);
      isReachable = true;
    } catch (IOException e) {
      log.error("FAILRE - CAN not connect! Local: "
          + localInetAddr.getHostAddress() + " remote: "
          + remoteInetAddr.getHostAddress() + " port" + port);
    } finally {
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException e) {
          log.error("Error occurred while closing socket:"
              + e.getMessage());
        }
      }
    }
    return isReachable;
  }
 
  /**
   * 測試localIp能否與遠程的主機指定端口建立連接相連
   *
   * @param localIp
   * @param remoteIp
   * @param port
   * @param timeout
   * @return
   */
  public boolean isReachable(String localIp, String remoteIp,
      int port, int timeout) {
    boolean isReachable = false;
    Socket socket = null;
    InetAddress localInetAddr = null;
    InetAddress remoteInetAddr = null;
    try {
      localInetAddr = InetAddress.getByName(localIp);
      remoteInetAddr = InetAddress.getByName(remoteIp);
      socket = new Socket();
      // 端口號設置為 0 表示在本地挑選一個可用端口進行連接
      SocketAddress localSocketAddr = new InetSocketAddress(
          localInetAddr, 0);
      socket.bind(localSocketAddr);
      InetSocketAddress endpointSocketAddr = new InetSocketAddress(
          remoteInetAddr, port);
      socket.connect(endpointSocketAddr, timeout);
      log.info("SUCCESS - connection established! Local: "
          + localInetAddr.getHostAddress() + " remote: "
          + remoteInetAddr.getHostAddress() + " port" + port);
      isReachable = true;
    } catch (IOException e) {
      log.error("FAILRE - CAN not connect! Local: "
          + localInetAddr.getHostAddress() + " remote: "
          + remoteInetAddr.getHostAddress() + " port" + port);
    } finally {
      if (socket != null) {
        try {
          socket.close();
        } catch (IOException e) {
          log.error("Error occurred while closing socket:"
              + e.getMessage());
        }
      }
    }
    return isReachable;
  }
 
  public static void main(String[] args) {
     if(NetworkHelper.getInstance().isReachIp("192.168.126.128")){
       log.info("=======本機可以ping通ip:"+"192.168.126.128");
     }
     else{
       log.info("=======本機ping不通ip:"+"192.168.126.128");
     }
     if(NetworkHelper.getInstance().isReachNetworkInterfaces("192.168.126.128")){
       log.info("=======本機所有網卡可以ping通ip:"+"192.168.126.128");
     }
     else{
       log.info("=======本機所有網卡ping不通ip:"+"192.168.126.128");
     }
     String localIp = NetworkHelper.getInstance().getReachableIP("192.168.126.128",8081);
     if(!StringUtils.isBlank(localIp)){
       log.info("=======本機可以與ip:"+"192.168.126.128"+",port:"+8081+"建立連接的IP:"+localIp);
     }
     else{
       log.info("=======本機不能與ip:"+"192.168.126.128"+",port:"+8081+"建立連接的IP");
     }
  }
 
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 亚洲男女在线 | 免费的强动漫人物 | 白丝超短裙被输出娇喘不停小说 | 国产精品免费久久久久影院小说 | 国产真实偷乱视频在线观看 | 成年人在线视频免费观看 | 日本在线视频网 | 色小妹在线 | 偷拍自拍校园春色 | 蜜月aⅴ免费一区二区三区 蜜桃影像传媒推广 | 国产麻豆精品视频 | 国产精品久久毛片完整版 | 免费观看无遮挡www的小视频 | 日本五级床片全都免费播放 | 国产国语在线播放视频 | 好紧好爽再叫浪一点点潘金莲 | 亚洲v日韩v欧美在线观看 | 古代双性美人被老糟蹋 | 国产精品福利 | 描写细腻的高h肉 | 8x8x拔插 | 久久精品男人影院 | 精品一区二区三区视频 | 2020国产精品视频免费 | 不卡一区二区三区 | xxxx野外性xxxx| 美女操批| 女子监狱第二季在线观看免费完整版 | 嫩模被黑人粗大挺进 | ass极品美妇pic | 狠狠干奇米 | 国产91一区二区在线播放不卡 | 精品日韩欧美一区二区三区在线播放 | 青草娱乐极品免费视频 | 国产 国语对白 露脸正在播放 | 啊好痛嗯轻一点免费 | 国产伦精品一区二区三区免费观看 | www.99精品视频在线播放 | 免费人成网址在线观看国内 | 本站只有精品 | 99久久精品国产片久人 |