기계의 IP 및 MAC 주소를 얻는 Java
일부 기계에는 많은 가상 네트워크 카드가 있으며 IP 주소를 얻을 때 일부 사고가 발생하므로 일부 검증이 필요합니다.
// MAC 주소 가져 오기 공개 정적 문자열 getMacAddress () {enumeration <NetworkInterface> allnetInterfaces = workinterface.getNetworkInterfaces (); 바이트 [] mac = null; while (allnetInterfaces.hasMoreElements ()) {NetworkInterface netInterface = (네트워크 인터페이스) allnetInterfaces.nextElement (); if (netinterface.isloopback () || netInterface.isvirtual () ||! netInterface.isup ()) {계속; } else {mac = netinterface.gethardWareaddress (); if (mac! = null) {StringBuilder sb = new StringBuilder (); for (int i = 0; i <mac.length; i ++) {sb.append (string.format ( "%02x%s", mac [i], (i <mac.length -1)? " -" "); } if (sb.length ()> 0) {return sb.toString (); }}}}} catch (예외 e) {_logger.error ( "Mac 주소 획득 실패", e); } 반품 ""; } // IP 주소 가져 오기 공개 static string getipAddress () {enumeration <networkinterface> allnetInterfaces = NetworkInterface.getNetworkInterfaces (); inetAddress ip = null; while (allnetInterfaces.hasMoreElements ()) {NetworkInterface netInterface = (네트워크 인터페이스) allnetInterfaces.nextElement (); if (netinterface.isloopback () || netInterface.isvirtual () ||! netInterface.isup ()) {계속; } else {열거 <inetAddress> 주소 = netInterface.getInetAddresses (); while (address.hasmoreElements ()) {ip = address.nextElement (); if (ip! = null && ip instanceof inet4address) {return ip.gethostaddress (); }}}}} catch (예외 e) {_logger.error ( "IP 주소 획득 실패", e); } 반품 ""; } 위 코드에서
NetInterface.isLoopback () || NetInterface.isvirtual () || ! netinterface.isup ()
비 물리 네트워크 카드 나 쓸모없는 네트워크를 잘 필터링 한 다음 인터넷에서 IPv4 주소를 검색 할 수 있습니다.
이것에 대해 말하면, 일반적으로 사용되는 몇 가지가 있습니다.
1. 현재 기계의 운영 체제를 얻으십시오
공개 최종 정적 문자열 win_os = "Windows"; 공개 최종 정적 문자열 mac_os = "mac"; 공개 최종 정적 문자열 linux_os = "Linux"; 공개 최종 정적 문자열 기타 _os = "기타"; public static string getos () {if (systemutils.is_os_windows) {return win_os; } if (systemUtils.is_os_mac || systemutils.is_os_mac_osx) {return mac_os; } if (systemUtils.is_os_unix) {return linux_os; } reture other_os; } 2. HTTP 액세스 프록시를 설정하십시오
/ *** SET HTTP 프록시*/ public static void sethttpproxy () {properties proper = system.getProperties (); // 사용될 프록시 서버의 주소에 액세스하도록 HTTP를 설정합니다. // prop.setProperty ( "http.proxyport", http_proxy_port); // 프록시 서버를 통해 액세스 할 필요가없는 호스트 설정 * 와일드 카드 문자를 사용할 수 있으며 여러 주소가 | prop.setproperty ( "http.nonproxyhosts", remoteconfig.proxt_filter_domain); } / *** HTTP 프록시 제거* / public static void remokhttpproxy () {properties proper = system.getProperties (); prop.remove ( "http.proxyhost"); prop.remove ( "http.proxyport"); prop.remove ( "http.nonproxyhost"); prop.remove ( "http.nonproxyhost"); } 애플리케이션이 시작되면 HTTP 요청에 액세스하기 전에 설정하십시오. 물론 HTTP.NONPROXYHOSTS는 설정없이 설정할 수 있습니다. 즉, 모든 HTTP 요청이 프록시됩니다.
HTTPS 프록시는 다음과 같이 설정할 수 있습니다.
System.setProperty ( "https.proxyhost", "http_proxy_host");
System.SetProperty ( "https.proxyport", "http_proxy_port");
위의 내용은 Java가 기본 IP 및 Mac을 얻는 예입니다. 도움이 필요한 친구들이 그것을 언급 할 수 있습니다. 이 사이트를 지원 해주셔서 감사합니다!