Java獲取本地IP方法
獲取本地服務器IP經常會出現127.0.0.1,0:0:0:0:0:0:0:1,fe80:0:0:0:960:74bd:e1a0:e5b9%11 這些情況,以下代碼可解決此問題
public static void main(String[] args) { try { Enumeration<NetworkInterface> enumeration = NetworkInterface .getNetworkInterfaces(); while (enumeration.hasMoreElements()) { NetworkInterface networkInterface = enumeration.nextElement(); if (networkInterface.isUp()) { Enumeration<InetAddress> addressEnumeration = networkInterface .getInetAddresses(); while (addressEnumeration.hasMoreElements()) { String ip = addressEnumeration.nextElement() .getHostAddress(); final String REGX_IP = "((25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)"; if (ip.matches(REGX_IP) && !ip.equals("127.0.0.1")) { System.out.println(ip); }} } } } catch (Exception e) { log.error("獲取本機ip出現異常,異常信息為:" + e.getMessage()); } }</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!