This article shares with you the Java method to test network connectivity for your reference. The specific content is as follows
The first method: use the java runtime:
Java code
/** * test network * @param ip */private void getNetworkState(String ip) { Runtime runtime = Runtime.getRuntime(); try { log.info("========================= 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 is normal, time: " + TimeUtil.getCurDate("yyyy-mm-dd hh:mm:ss")); } else { log.info("Network is disconnected, time:" + TimeUtil.getCurDate("yyyy-mm-dd hh:mm:ss")); } } } catch (Exception e) { log.error("Network exception: "+e.getMessage()); e.printStackTrace(); }} On the Windows platform, the above code is not used, and ping ip will end. However, when the ping command is not working in the Linux environment,
It will be stuck, ping, and output information in uncertain ways. Consider using another way to socket.
The second way to 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.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.getLogger(NetworkHelper.class); private static NetworkHelper instance = null; public static synchronized NetworkHelper getInstance(){ if(instance == null){ instance = new NetworkHelper(); } return instance; } /** * Test whether local 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; } /** * Test all local network card addresses to ping the 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("----------------"); 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; } /** * Get the native IP address that can establish a connection to the specified port of the remote host* @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; } /** * Get the native IP address that can establish a connection with the specified port of the remote host* @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; } /** * Test whether localInetAddr can establish a connection with the 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(); // Set the port number to 0 to indicate that you select an available port locally for connection. 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; } /** * Test whether localIp can establish a connection with the remote host specified port* * @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(); // Set the port number to 0 to indicate that you select an available port locally for connection. 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("========Native can ping the ip: "+"192.168.126.128"); } else{ log.info("=========Native ping does not ping the ip: "+"192.168.126.128"); } if(NetworkHelper.getInstance().isReachNetworkInterfaces("192.168.126.128"))){ log.info("========= All network cards in the machine can ping the IP: "+"192.168.126.128"); } else{ log.info("======== All network cards in the machine cannot ping the IP: "+"192.168.126.128"); } String localIp = NetworkHelper.getInstance().getReachableIP("192.168.126.128",8081); if(!StringUtils.isBlank(localIp)){ log.info("=========Native machine can establish an IP for connection with ip: "+"192.168.126.128"+",port:"+8081+": "+localIp); } else{ log.info("=======Native machine can not establish an IP for connection with ip: "+"192.168.126.128"+",port:"+8081+""); } }} The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.