欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java如何测试网络连通性

程序员文章站 2024-03-12 19:14:32
本文实例为大家分享了java测试网络连通性的方法,供大家参考,具体内容如下 第一种方式:利用java运行时: java代码 /** * test...

本文实例为大家分享了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");
     }
  }

}

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