How Java Tests network connectivity _java

Source: Internet
Author: User
Tags getmessage stringbuffer

The example of this article for everyone to share the Java Test network connectivity methods for your reference, the specific contents are as follows

The first way: Using the Java Runtime:
Java code

 /** * Test Network * @param IP/private void getnetworkstate (String IP) {Runtime Runtime = Runtime.getruntime ();
    try {log.info ("================= is testing network connectivity 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 (     
      "Network Normal, Time:" + timeutil.getcurdate ("Yyyy-mm-dd hh:mm:ss")); else {log.info ("Network Disconnected, Time:" + timeutil.getcurdate ("Yyyy-mm-dd hh: Mm:ss "));
    (Exception e) {log.error ("Network exception:" +e.getmessage ());
  E.printstacktrace ();

 }
}

On the Windows platform, the above code does not, ping IP will end, and in the Linux Environment ping command, Ping impassability,
Will be stuck, Ping pass, will be uncertain output information, consider using a different way socket.

Second WAY socket:
Java code

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; /** * Test Network connectivity * * @author Donald */public class Networkhelper {private static Logger log = Loggerfactory.getl
  Ogger (Networkhelper.class);
  private static Networkhelper instance = NULL;
    public static synchronized Networkhelper getinstance () {if (instance = = null) {instance = new Networkhelper ();

  return instance; /** * Test whether local can ping IP * * @param IP * @return/public boolean isreachip (String IP) {Boolean is
    reach = 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");
    The catch (Exception e) {log.error ("error occurs:" + e.getmessage ());
  return Isreach; /** * Test all local network card addresses can ping IP * * @param IP * @return/public boolean isreachnetworkinterfaces (stri
    ng IP) {Boolean isreach = false; try {inetaddress address = Inetaddress.getbyname (IP);//Ping this IP if (address instanceof java.net.Inet4Ad
      Dress) {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 are done--------------------------");
    The catch (Exception e) {log.error ("error occurs:" + e.getmessage ());
  return Isreach; /** * Gets the native IP address that can establish a connection with the specified port of the remote host * @param remoteaddr * @param port * @return/public String Getreacha
    Bleip (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 SocketException e) {log.error ("error occurred while listing all"
    Addresses: "+ e.getmessage ());
    } if (Retip = = null) {Log.info ("null reachable local IP is found!");
    else {log.info ("reachable local IP be found, it is" + retip);
  return retip; /** * Gets the native IP address that can establish a connection with the specified port of the remote host * @param REMOTEIP * @param port * @return/public String getreachable
    IP (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 Unknownhostexception e) {log.error ("error occurred while listing all"
    Work addresses: "+ e.getmessage ()); }catch (SocketException e) {log.error ("error occurred while listing all of the local network addresses:" + e.getmessage
    ());
    } if (Retip = = null) {Log.info ("null reachable local IP is found!");
    else {log.info ("reachable local IP be found, it is" + retip);
  return retip; /** * Test localinetaddr can be connected to a remote host specified port * * @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 ();
      The port number set to 0 indicates that an available port is selected locally to connect 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; The 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; /** * Test Localip can establish a connection with a remote host specified port * * @param localip * @param remoteip * @param port * @param time Out * @return */public boolean isreachable (String Localip, string remoteip, int port, int timeout) {bo
    Olean isreachable = false;
    Socket socket = NULL;
    InetAddress localinetaddr = null;
    InetAddress remoteinetaddr = null;
      try {localinetaddr = Inetaddress.getbyname (Localip);
      REMOTEINETADDR = Inetaddress.getbyname (REMOTEIP);
      Socket = new socket ();
      The port number set to 0 indicates that an available port is selected locally to connect 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; The 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")) {Lo
     G.info ("======= This machine can ping through IP:" + "192.168.126.128"); else{log.info ("======= native ping does not pass IP:" + "192.168.126.128 "); } if (Networkhelper.getinstance (). Isreachnetworkinterfaces ("192.168.126.128")) {Log.info ("======= All network adapters can ping I
     P: "+" 192.168.126.128 ");
     else{Log.info ("======= all network card ping not pass IP:" + "192.168.126.128");
     String Localip = Networkhelper.getinstance (). GETREACHABLEIP ("192.168.126.128", 8081); if (!
     Stringutils.isblank (Localip)) {log.info ("======= native can be associated with IP: +" 192.168.126.128 "+", Port: "+8081+" to establish a connected IP: "+localip);"
     else{Log.info ("======= This machine can not be connected with IP: +" 192.168.126.128 "+", Port: "+8081+" to establish a connecting IP);
 }
  }

}

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.