最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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)程主機指定端口建立連接的本機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)程主機指定端口建立連接的本機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)程的主機指定端口建立連接相連
   * 
   * @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 表示在本地挑選一個可用端口進行連接
      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)程的主機指定端口建立連接相連
   * 
   * @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 表示在本地挑選一個可用端口進行連接
      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("=======本機所有網(wǎng)卡可以ping通ip:"+"192.168.126.128");
     }
     else{
       log.info("=======本機所有網(wǎng)卡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");
     }
  }

}

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

相關(guān)文章

  • mybatis動態(tài)sql之Map參數(shù)的講解

    mybatis動態(tài)sql之Map參數(shù)的講解

    今天小編就為大家分享一篇關(guān)于mybatis動態(tài)sql之Map參數(shù)的講解,小編覺得內(nèi)容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • Spring@Value屬性注入使用方法解析

    Spring@Value屬性注入使用方法解析

    這篇文章主要介紹了Spring@Value屬性注入使用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-01-01
  • 如何解決IDEA沒有新建servlet選項問題

    如何解決IDEA沒有新建servlet選項問題

    這篇文章主要介紹了如何解決IDEA沒有新建servlet選項問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2025-04-04
  • Springboot通過lucene實現(xiàn)全文檢索詳解流程

    Springboot通過lucene實現(xiàn)全文檢索詳解流程

    Lucene是一個基于Java的全文信息檢索工具包,它不是一個完整的搜索應(yīng)用程序,而是為你的應(yīng)用程序提供索引和搜索功能。Lucene 目前是 Apache Jakarta 家族中的一個開源項目,也是目前最為流行的基于 Java 開源全文檢索工具包
    2022-06-06
  • Spring?Aop+Redis實現(xiàn)優(yōu)雅記錄接口調(diào)用情況

    Spring?Aop+Redis實現(xiàn)優(yōu)雅記錄接口調(diào)用情況

    通常情況下,開發(fā)完一個接口,無論是在測試階段還是生產(chǎn)上線,我們都需要對接口的執(zhí)行情況做一個監(jiān)控,所以本文為大家整理了Spring統(tǒng)計接口調(diào)用的多種方法,希望對大家有所幫助
    2023-06-06
  • Java去掉小數(shù)點后面無效0的方案與建議

    Java去掉小數(shù)點后面無效0的方案與建議

    當(dāng)前小數(shù)點后面的位數(shù)過多的時候,多余的0沒有實際意義,下面這篇文章主要給大家介紹了關(guān)于Java去掉小數(shù)點后面無效0的方案與建議,文中通過示例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-07-07
  • SpringBoot項目啟動時增加自定義Banner的簡單方法

    SpringBoot項目啟動時增加自定義Banner的簡單方法

    最近看到springboot可以自定義啟動時的banner,然后自己試了一下,下面這篇文章主要給大家介紹了SpringBoot項目啟動時增加自定義Banner的簡單方法,需要的朋友可以參考下
    2022-01-01
  • 如何安裝jdk及安裝MyEclipse的圖文教程

    如何安裝jdk及安裝MyEclipse的圖文教程

    這篇文章主要介紹了如何安裝jdk及安裝MyEclipse的圖文教程,需要的朋友可以參考下
    2018-03-03
  • RocketMQ?Push?消費模型示例詳解

    RocketMQ?Push?消費模型示例詳解

    這篇文章主要為大家介紹了RocketMQ?Push?消費模型示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2022-09-09
  • Java中使用注解獲取和改變Bean的指定變量值

    Java中使用注解獲取和改變Bean的指定變量值

    Java有時需要通過自定義注解,獲取某Bean的某變量的值,根據(jù)業(yè)務(wù)要求處理數(shù)據(jù),然后再把新值設(shè)置回Bean的同一變量中,這篇文章介紹了使用注解獲取和改變Bean變量值的過程,感興趣想要詳細(xì)了解可以參考下文
    2023-05-05

最新評論

昌图县| 屏东市| 泗水县| 舟山市| 安新县| 射阳县| 和平区| 宜川县| 咸丰县| 邵阳市| 康平县| 大洼县| 武夷山市| 永清县| 葫芦岛市| 北碚区| 丹江口市| 元谋县| 河南省| 灵石县| 合水县| 乃东县| 阳江市| 庆云县| 特克斯县| 前郭尔| 浦北县| 东莞市| 临洮县| 淮北市| 密云县| 闻喜县| 盐边县| 潮州市| 霍邱县| 鄄城县| 庆阳市| 剑阁县| 都匀市| 宜州市| 繁峙县|