欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java如何測試網(wǎng)絡(luò)連通性

 更新時間:2016年10月25日 11:09:56   投稿:lijiao  
這篇文章主要為大家詳細(xì)介紹了java測試網(wǎng)絡(luò)連通性的兩種方式,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了Java測試網(wǎng)絡(luò)連通性的方法,供大家參考,具體內(nèi)容如下

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

 /**
 * test network
 * @param ip
 */
private void getNetworkState(String ip) {
  Runtime runtime = Runtime.getRuntime();
  try {
    log.info("=================正在測試網(wǎng)絡(luò)連通性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("網(wǎng)絡(luò)正常,時間: " + TimeUtil.getCurDate("yyyy-mm-dd hh:mm:ss"));     
      } else {
        log.info("網(wǎng)絡(luò)斷開,時間 :" + TimeUtil.getCurDate("yyyy-mm-dd hh:mm:ss"));

      }
    }
  } catch (Exception e) {
    log.error("網(wǎng)絡(luò)異常:"+e.getMessage());
    e.printStackTrace();
  }
}

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

第二種方式socket:
Java代碼

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;

/**
 * 測試網(wǎng)絡(luò)連通性
 * 
 * @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;
  }

  /**
   * 測試本地所有的網(wǎng)卡地址都能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;
  }

  /**
   * 獲取能與遠(yuǎn)程主機(jī)指定端口建立連接的本機(jī)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;
  }
  /**
   * 獲取能與遠(yuǎn)程主機(jī)指定端口建立連接的本機(jī)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能否與遠(yuǎn)程的主機(jī)指定端口建立連接相連
   * 
   * @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();
      // 端口號設(shè)置為 0 表示在本地挑選一個可用端口進(jìn)行連接
      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能否與遠(yuǎn)程的主機(jī)指定端口建立連接相連
   * 
   * @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();
      // 端口號設(shè)置為 0 表示在本地挑選一個可用端口進(jìn)行連接
      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("=======本機(jī)可以ping通ip:"+"192.168.126.128");
     }
     else{
       log.info("=======本機(jī)ping不通ip:"+"192.168.126.128");
     }
     if(NetworkHelper.getInstance().isReachNetworkInterfaces("192.168.126.128")){
       log.info("=======本機(jī)所有網(wǎng)卡可以ping通ip:"+"192.168.126.128");
     }
     else{
       log.info("=======本機(jī)所有網(wǎng)卡ping不通ip:"+"192.168.126.128");
     }
     String localIp = NetworkHelper.getInstance().getReachableIP("192.168.126.128",8081);
     if(!StringUtils.isBlank(localIp)){
       log.info("=======本機(jī)可以與ip:"+"192.168.126.128"+",port:"+8081+"建立連接的IP:"+localIp);
     }
     else{
       log.info("=======本機(jī)不能與ip:"+"192.168.126.128"+",port:"+8081+"建立連接的IP");
     }
  }

}

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java源碼解析之詳解ReentrantLock

    Java源碼解析之詳解ReentrantLock

    今天給大家?guī)淼氖顷P(guān)于Java并發(fā)的相關(guān)知識,文章圍繞著ReentrantLock源碼展開,文中有非常詳細(xì)的介紹及代碼示例,需要的朋友可以參考下
    2021-06-06
  • Java并發(fā)編程中的Exchanger解析

    Java并發(fā)編程中的Exchanger解析

    這篇文章主要介紹了Java并發(fā)編程中的Exchanger解析,Exchanger用于線程間數(shù)據(jù)的交換,它提供一個同步點,在這個同步點,兩個線程可以交換彼此的數(shù)據(jù),這兩個線程通過exchange方法交換數(shù)據(jù),如果第一個線程先執(zhí)行exchange()方法,需要的朋友可以參考下
    2023-11-11
  • springBoot 打war包 程序包com.sun.istack.internal不存在的問題及解決方案

    springBoot 打war包 程序包com.sun.istack.internal不存在的問題及解決方案

    這篇文章主要介紹了springBoot 打war包 程序包com.sun.istack.internal不存在的問題及解決方案,親測試過可以,需要的朋友可以參考下
    2018-07-07
  • spring Boot查詢數(shù)據(jù)分頁顯示的方法實例

    spring Boot查詢數(shù)據(jù)分頁顯示的方法實例

    這篇文章主要給大家介紹了關(guān)于spring Boot查詢數(shù)據(jù)分頁顯示的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用spring Boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-08-08
  • Mybatis學(xué)習(xí)總結(jié)之mybatis使用建議

    Mybatis學(xué)習(xí)總結(jié)之mybatis使用建議

    這篇文章主要介紹了Mybatis學(xué)習(xí)總結(jié)之mybatis使用建議的相關(guān)資料,非常具有參考借鑒價值,需要的朋友可以參考下
    2016-05-05
  • Java中的邏輯控制語句詳解

    Java中的邏輯控制語句詳解

    下面小編就為大家?guī)硪黄狫ava邏輯控制的基礎(chǔ)文章。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2021-08-08
  • Java注解詳解之@Override注解

    Java注解詳解之@Override注解

    這篇文章主要給大家介紹了關(guān)于Java注解之@Override注解的相關(guān)資料,@Override是Java中的一個注解,表示一個方法是重寫(Override)了父類中的方法,文中通過代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-11-11
  • Java實現(xiàn)斷點下載服務(wù)端與客戶端的示例代碼

    Java實現(xiàn)斷點下載服務(wù)端與客戶端的示例代碼

    這篇文章主要為大家介紹了如何實現(xiàn)服務(wù)端(Spring Boot)與客戶端(Android)的斷點下載與下載續(xù)傳功能,文中的示例代碼講解詳細(xì),需要的可以參考一下
    2022-08-08
  • Java編程訪問權(quán)限的控制代碼詳解

    Java編程訪問權(quán)限的控制代碼詳解

    這篇文章主要介紹了Java編程訪問權(quán)限的控制代碼詳解,涉及包名,公共的和私有的等相關(guān)內(nèi)容,分享了相關(guān)代碼示例,小編覺得還是挺不錯的,具有一定借鑒價值,需要的朋友可以參考下
    2018-01-01
  • Java8的DateTimeFormatter與SimpleDateFormat的區(qū)別詳解

    Java8的DateTimeFormatter與SimpleDateFormat的區(qū)別詳解

    這篇文章主要介紹了Java8的DateTimeFormatter與SimpleDateFormat的區(qū)別詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03

最新評論