当前位置: 首页 > 编程笔记 >

java如何测试网络连通性

白哲茂
2023-03-14
本文向大家介绍java如何测试网络连通性,包括了java如何测试网络连通性的使用技巧和注意事项,需要的朋友参考一下

本文实例为大家分享了Java测试网络连通性的方法,供大家参考,具体内容如下

第一种方式:利用java运行时:
Java代码

 /**
 * 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代码

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");
     }
  }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持小牛知识库。

 类似资料:
  • 问题内容: 通常的问题是如何模拟(作为一组测试用例的一部分)缺乏网络连接,因为这是某些测试用例中的重要考虑因素。有没有一种方法可以通过Java API(或通过JVM选项)来执行,以便某些测试用例可以在网络断开的情况下运行?(模拟还是真实?)。 更具体的情况(如果没有普遍适用的解决方案)是我正在做大量的XML文件处理(包括XSD验证),并且我需要确保没有从网络上获取任何内容,特别是属性值(提示)未使

  • Hello! 我在开发板上部署了snort这个ids,希望测试它的性能。 是它在这个开发板分析数据包的速度,效率(并不是它被配置的规则能多么有效全面地挡住任何种类的攻击) 但,我搜了个ftester,但好像已经过时了。搜了个pytbull,但它要求在被攻击机器上也运行python,而我这个开发板装个snort已经是费劲力气了。 还有什么软件或者存在在这个场合有意义了?

  • 网络渗透测试是将在本节中介绍的第一个渗透测试。大多数系统和计算机都连接到网络。如果设备连接到互联网,这意味着设备已连接到网络,因为互联网是一个非常大的网络。因此,我们需要知道设备如何在网络中相互交互,以及网络如何工作。 网络渗透测试分为3个小部分: 预连接攻击:在本节中,我们将了解在连接到网络之前可以执行的所有攻击。 获得攻击:在本节中,我们将了解如何破解Wi-Fi密钥并获取Wi-Fi网络,无论使

  • 欢迎使用 EOS Party 测试网络 英文介绍: https://github.com/eostea/EOS-Party-Testnet Party 是一个基于https://github.com/EOS-Mainnet/eos 的一个小规模测试网络, 网络的 BP 数量目前设置成 7 个, 并且均由可信团队部署 (这是一个团队内部的测试网络). 如果你需要一个规模更大或者更接近主网的测试环境,

  • Hyperledger Composer支持三种类型的测试:交互式测试、自动化单元测试和自动系统测试。三者都有不同的用途,对于确保区块链项目的成功至关重要。 在部署了业务网络定义之后,通常运行一个互动的“冒烟测试”以确保部署成功。为了运行这样的冒烟测试,composerCLI暴露了几个命令。 另一方面,你可以使用Docker Compose和Mocha/Chai编写完整的系统测试,这些测试启动运行

  • 在磁盘根目录创建一个文件夹(用英文名) 进入文件夹,右键打开bash 下载数据库:git clone https://github.com/lengzhao/database.git 进入database文件夹,编译数据库: ./upgrade.sh 修改数据库的服务端口: cp conf.json.bak conf.json sed -i '/17777/47777/' conf.json