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

}

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

(0)

相关推荐

  • Powershell实现监测服务器连通状态

    工作中可能会遇到有几台托管的服务器,比如数据库,一旦网络中断就会影响到数据采集. 为此你可以使用下面脚本,它用计划任务每小时执行一次,一旦服务器出现断网,则会弹出提示窗口,代码如下: 复制代码 代码如下: $computerNames = @("10.3.X.56","10.0.XX.123")  $computerNames|%{     if(!(Test-Connection -ComputerName $_ -Quiet )){         cmd /c

  • java网络编程之socket网络编程示例(服务器端/客户端)

    Java为TCP协议提供了两个类,分别在客户端编程和服务器端编程中使用它们.在应用程序开始通信之前,需要先创建一个连接,由客户端程序发起:而服务器端的程序需要一直监听着主机的特定端口号,等待客户端的连接.在客户端中我们只需要使用Socket实例,而服务端要同时处理ServerSocket实例和Socket实例;二者并且都使用OutputStream和InpuStream来发送和接收数据. 学习一种知识最好的方式就是使用它,通过前面的笔记,我们已经知道如何获取主机的地址信息,现在我们通过一个简单的

  • Java实现爬虫给App提供数据(Jsoup 网络爬虫)

    一.需求 最近基于 Material Design 重构了自己的新闻 App,数据来源是个问题. 有前人分析了知乎日报.凤凰新闻等 API,根据相应的 URL 可以获取新闻的 JSON 数据.为了锻炼写代码能力,笔者打算爬虫新闻页面,自己获取数据构建 API. 二.效果图 下图是原网站的页面 爬虫获取了数据,展示到 APP 手机端 三.爬虫思路 关于App 的实现过程可以参看这几篇文章,本文主要讲解一下如何爬虫数据. Android下录制App操作生成Gif动态图的全过程 :http://www

  • java网络编程学习java聊天程序代码分享

    复制代码 代码如下: package com.neusoft.edu.socket;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.PrintWriter;import java.net.ServerSocket;import java.net.Socket;/** * 服务器端代码 * 获取客户端发送的信息,显示并且返回对应的回复 *

  • java使用TimerTask定时器获取指定网络数据

    复制代码 代码如下: import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.net.URL;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Timer;import java.util.TimerTask; public class GetYinInf

  • Java获取网络文件并插入数据库的代码

    获取百度的歌曲名,歌手和链接!! 复制代码 代码如下: package webTools; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import

  • Java网络编程基础教程之Socket入门实例

    当我们想要在Java中使用TCP/IP通过网络连接到服务器时,就需要创建java.net.Socket对象并连接到服务器.假如希望使用Java NIO,也可以创建Java NIO中的SocketChannel对象. 创建Socket 下面的示例代码是连接到IP地址为78.64.84.171服务器上的80端口,这台服务器就是我们的Web服务器(www.jb51.net),而80端口就是Web服务端口. 复制代码 代码如下: Socket socket = new Socket("78.46.84.

  • Java用文件流下载网络文件示例代码

    复制代码 代码如下: public HttpServletResponse download(String path, HttpServletResponse response) {        try {            // path是指欲下载的文件的路径.            File file = new File(path);            // 取得文件名.            String filename = file.getName();          

  • 简单介绍Java网络编程中的HTTP请求

    HTTP请求的细节--请求行   请求行中的GET称之为请求方式,请求方式有:POST.GET.HEAD.OPTIONS.DELETE.TRACE.PUT,常用的有: GET. POST 用户如果没有设置,默认情况下浏览器向服务器发送的都是get请求,例如在浏览器直接输地址访问,点超链接访问等都是get,用户如想把请求方式改为post,可通过更改表单的提交方式实现. 不管POST或GET,都用于向服务器请求某个WEB资源,这两种方式的区别主要表现在数据传递上:如果请求方式为GET方式,则可以在请

  • java网络编程中向指定URL发送GET POST请求示例

    复制代码 代码如下: import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.OutputStream;import java.io.PrintWriter;import java.net.HttpURLConnection;import java.net.URL;import java.net.URLConnection;import jav

随机推荐