이 기사는 귀하의 참조에 대한 네트워크 연결을 테스트하는 Java 메소드를 공유합니다. 특정 내용은 다음과 같습니다
첫 번째 방법 : Java 런타임 사용 :
자바 코드
/** * 테스트 네트워크 * @param ip */private void getNetworkState (String IP) {런타임 런타임 = runtime.getRuntime (); try {log.info ( "======================== 네트워크 연결 테스트 IP :"+IP); 프로세스 프로세스 = runtime.exec ( "Ping" +IP); inputStream istream = process.getInputStream (); inputStreamReader isReader = new inputStreamReader (istream, "utf-8"); BufferedReader Breader = New BufferedReader (IsReader); 문자열 라인 = null; StringBuffer sb = new StringBuffer (); while ((line = breader.readline ())! = null) {sb.append (line); } istream.close (); isreader.close (); breader.close (); 문자열 result = new String (sb.toString (). getBytes ( "UTF-8")); log.info ( "핑 결과 :"+결과); 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 (예외 e) {log.error ( "네트워크 예외 :"+e.getMessage ()); e.printstacktrace (); }} Windows 플랫폼에서 위의 코드는 사용되지 않으며 Ping IP는 종료됩니다. 그러나 Ping 명령이 Linux 환경에서 작동하지 않을 때는
불확실한 방식으로 고정, 핑 및 출력 정보가있을 것입니다. 소켓에 다른 방법을 사용하는 것을 고려하십시오.
소켓의 두 번째 방법 :
자바 코드
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.socket.socket.net.socketaddress; import java.net.socketexceme java.net.unknownhostexception; import java.util.enumeration; import org.apache.commons.lang.stringutils; import org.slf4j.logger; import org.slf4j.loggerfactory;/** * @author log */public class networkhelper {private class networkhelper {private classe networkhelper {private classe networkhelper loggerfactory.getLogger (NetworkHelper.class); 개인 정적 네트워크 헬퍼 인스턴스 = null; public static synchronized networkHelper getInstance () {if (instance == null) {instance = new NetworkHelper (); } return 인스턴스; } / ** * 로컬 핑 IP * * @param ip * @return * / public boolean isreachip (문자열 IP) {boolean isreach = false; try {inetAddress address = inetAddress.getByName (ip); // this ip if (java.net.inet4address의 주소 인스턴스) {log.info (ip + "IS IPv4 주소"); } else if (java.net.inet6address의 주소 인스턴스) {log.info (ip + "IS IPv6 주소"); } else {log.info (ip + "는 정지되지 않습니다"); } if (address.isreachable (5000)) {isreach = true; log.info ( "성공 -Ping" + IP + "인터페이스가 지정되지 않은"); } else {isreach = false; log.info ( "실패 -Ping" + IP + "인터페이스가 지정되지 않은"); }} catch (예외 e) {log.error ( "오류가 발생합니다 :" + e.getMessage ()); } 반환 ISREACH; } / ** * 모든 로컬 네트워크 카드 주소를 Ping to Ip * @param ip * @return * / public boolean isreachnetworkinterfaces (String IP) {boolean isreach = false; try {inetAddress address = inetAddress.getByName (ip); // this ip if (java.net.inet4address의 주소 인스턴스) {log.info (ip + "IS IPv4 주소"); } else if (java.net.inet6address의 주소 인스턴스) {log.info (ip + "IS IPv6 주소"); } else {log.info (ip + "는 정지되지 않습니다"); } if (address.isreachable (5000)) {isreach = true; log.info ( "성공 -Ping" + IP + "인터페이스가 지정되지 않은"); } else {isreach = false; log.info ( "실패 -Ping" + IP + "인터페이스가 지정되지 않은"); } if (isreach) {log.info ( "---------------"); 열거 <TOMWANKINTERFACE> netInterfaces = NetworkInterface .getNetWorkInterfaces (); while (netInterfaces.hasmoreElements ()) {NetworkInterface ni = netInterfaces.nextElement (); log.info ( "확인 인터페이스, displayName :" + ni.getDisplayName () + ", 이름 :" + ni.getName ()); if (address.isreachable (ni, 0, 5000)) {isreach = true; log.info ( "성공 -Ping" + IP); } else {isreach = false; log.info ( "실패 -Ping" + IP); } 열거 <InetAddress> ips = ni.getInetAddresses (); while (ips.hasmoreElements ()) {log.info ( "ip :" + ips.nextElement (). gethostAddress ()); } log.info ( "---------------- 지금 확인 네트워크 인터페이스가 완료 되었음 --------------------------------------------------------------------------------. }}} catch (예외 e) {log.error ( "오류가 발생합니다 :" + e.getMessage ()); } 반환 ISREACH; } / ** * 원격 호스트의 지정된 포트에 연결할 수있는 기본 IP 주소를 가져옵니다 * @param remoteaddr * @param port * @return * / public string getReachableIP (inetAddress remoteaddr, int port) {String retip = null; 열거 <WetworkInterface> NetInterfaces; {netInterfaces = NetworkInterface.getNetWorkInterfaces (); while (netInterfaces.hasmoreElements ()) {NetworkInterface ni = netInterfaces.nextElement (); 열거 <InetAddress> localAddrs = ni.getInetAddresses (); while (localAddrs.hasmoreElements ()) {inetAddress localAddr = localAddrs.nextElement (); if (isreachable (localAddr, remoteaddr, port, 5000)) {retip = localAddr.gethostAddress (); 부서지다; }}}} catch (pocketexception e) {log.error ( "모든 로컬 네트워크 주소를 나열하는 동안 오류가 발생했습니다." + e.getMessage ()); } if (retip == null) {log.info ( "null 도달 가능한 로컬 IP가 발견되었습니다!"); } else {log.info ( "도달 가능한 로컬 IP가 발견됩니다." + retip); } return retip; } / ** * 원격 호스트의 지정된 포트와 연결할 수있는 기본 IP 주소를 가져옵니다 * @param remotip * @param port * @return * / public string getReachableIP (String remotip, int port) {String retip = null; inetAddress remoteaddr = null; 열거 <WetworkInterface> NetInterfaces; {remoteaddr = inetAddress.getByName (remoteip); netInterfaces = NetworkInterface.getNetWorkInterfaces (); while (netInterfaces.hasmoreElements ()) {NetworkInterface ni = netInterfaces.nextElement (); 열거 <InetAddress> localAddrs = ni.getInetAddresses (); while (localAddrs.hasmoreElements ()) {inetAddress localAddr = localAddrs.nextElement (); if (isreachable (localAddr, remoteaddr, port, 5000)) {retip = localAddr.gethostAddress (); 부서지다; }}}} catch (unknownHostException e) {log.error ( "모든 로컬 네트워크 주소를 나열하는 동안 오류가 발생했습니다."+ e.getMessage ()); } catch (socketexception e) {log.error ( "모든 로컬 네트워크 주소를 나열하는 동안 오류가 발생했습니다."+ e.getMessage ()); } if (retip == null) {log.info ( "null 도달 가능한 로컬 IP가 발견되었습니다!"); } else {log.info ( "도달 가능한 로컬 IP가 발견됩니다." + retip); } return retip; } / ** * LocalInetAddr이 원격 호스트 지정된 포트와 연결할 수 있는지 테스트 * @param localInetAddr * @param remoteInetAddr * @param port * @param timeout * @return * / public boolean isreachable (inetAddress localInetaddr, inetAddress attreaminetAddr, int timeout) {boolean isrecable isrecable is recable; 소켓 소켓 = null; try {socket = new Socket (); // 포트 번호를 0으로 설정하여 연결할 수있는 사용 가능한 포트를 선택했음을 나타냅니다. SocketAddress localsocketAddr = 새로운 inetSocketAddress (LocalInetAddr, 0); Socket.bind (localsocketaddr); inetSocketAddress endPoinTsocketAddr = 새로운 inetSocketAddress (remoteInetAddr, 포트); socket.connect (endpointsocketaddr, timeout); log.info ( "성공 - 연결 설정! 로컬 :" + localInetAddr.gethostAddress () + "원격 :" + remoteInetAddr.gethostAddress () + "포트" + 포트); isreachable = true; } catch (ioException e) {log.error ( "실패 - 연결할 수 없습니다! 로컬 :" + localInetAddr.gethostAddress () + "remote :" + remoteInetAddr.gethostAddress () + "port" + port); } 마지막으로 {if (socket! = null) {try {socket.close (); } catch (ioexception e) {log.error ( "소켓을 닫는 동안 오류가 발생했습니다 :" + e.getMessage ()); }}} isreachable을 반환합니다. } / ** * LocalIP가 원격 호스트 지정된 원격 호스트와 연결을 설정할 수 있는지 테스트 * @param localip * @param remotip * @param port * @param timeout * @return * / public boolean iseachable (String localip, String remoteip, int port, int timeout) {boolean isreachable = false; 소켓 소켓 = null; inetAddress localInetAddr = null; inetAddress impleinetAddr = null; try {localInetAddr = inetAddress.getByName (localIP); RemoteInetAddr = inetAddress.getByName (remoteip); 소켓 = 새로운 소켓 (); // 포트 번호를 0으로 설정하여 연결할 수있는 사용 가능한 포트를 선택했음을 나타냅니다. SocketAddress localsocketAddr = 새로운 inetSocketAddress (LocalInetAddr, 0); Socket.bind (localsocketaddr); inetSocketAddress endPoinTsocketAddr = 새로운 inetSocketAddress (remoteInetAddr, 포트); socket.connect (endpointsocketaddr, timeout); log.info ( "성공 - 연결 설정! 로컬 :" + localInetAddr.gethostAddress () + "원격 :" + remoteInetAddr.gethostAddress () + "포트" + 포트); isreachable = true; } catch (ioException e) {log.error ( "실패 - 연결할 수 없습니다! 로컬 :" + localInetAddr.gethostAddress () + "remote :" + remoteInetAddr.gethostAddress () + "port" + port); } 마지막으로 {if (socket! = null) {try {socket.close (); } catch (ioexception e) {log.error ( "소켓을 닫는 동안 오류가 발생했습니다 :" + e.getMessage ()); }}} isreachable을 반환합니다. } public static void main (String [] args) {if (네트워크 helper.getInstance (). isreachip ( "192.168.126.128"))) {log.info ( "======= 원시 IP :"+"192.168.126.128"); } else {log.info ( "========== 네이티브 핑은 IP를 핑하지 않습니다 :"+"192.168.126.128"); } if (NetworkHelper.getInstance (). isreachnetWorkInterfaces ( "192.168.126.128"))) {log.info ( "======== 시스템의 모든 네트워크 카드는 IP를 ping 할 수 있습니다 :"+"192.168.126.128"); } else {log.info ( "======== 시스템의 모든 네트워크 카드는 IP를 핑할 수 없습니다 :"+"192.168.126.128"); } string localip = networkHelper.getInstance (). getReachableIP ( "192.168.126.128", 8081); if (! stringUtils.isblank (localip)) {log.info ( "========== 기본 머신은 IP와의 연결을 위해 IP를 설정할 수 있습니다 :"+"192.168.126.128"+", 포트 :"+8081+ ":"+localip); } else {log.info ( "======= 기본 머신은 IP와의 연결을 위해 IP를 설정할 수 없습니다 :"+"192.168.126.128"+", 포트 :"+8081+ ""; }}} 위는이 기사의 모든 내용입니다. 모든 사람의 학습에 도움이되기를 바랍니다. 모든 사람이 wulin.com을 더 지원하기를 바랍니다.