1.源碼: package com.jindian.spingbootecharts.controller; import org.springframework.stereotype.Controller; import java.net.*; import java.util.Enumeration; /** * @author tank * @Description: * @create 2019-04-11 9:33 **/ @Controller public class TestController { //獲取本機的IP地址 public static void main(String[] args) { //address1(); try { final InetAddress localHostLANAddress = getLocalHostLANAddress(); System.out.println("localHostLANAddress="+localHostLANAddress.getHostAddress()); } catch (Exception e) { e.printStackTrace(); } } //方式一:只能在Windows下使用 public static void address(){ try { final InetAddress localHost = InetAddress.getLocalHost(); // final String hostAddress = InetAddress.getLocalHost().getHostAddress(); System.out.println("本機地址爲:"+localHost); } catch (UnknownHostException e) { e.printStackTrace(); } } //方式二:windows下會產生多個值(不準確) public static void address1() { try{ Enumeration allNetInterfaces = NetworkInterface.getNetworkInterfaces(); InetAddress ip = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement(); System.out.println(netInterface.getName()); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof Inet4Address) { System.out.println("本機的IP = " + ip.getHostAddress()); } } } } catch (SocketException e) { e.printStackTrace(); } } //正確方法 public static InetAddress getLocalHostLANAddress() { try { InetAddress candidateAddress = null; // 遍歷所有的網絡接口 for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) { NetworkInterface iface = (NetworkInterface) ifaces.nextElement(); // 在所有的接口下再遍歷IP for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) { InetAddress inetAddr = (InetAddress) inetAddrs.nextElement(); if (!inetAddr.isLoopbackAddress()) {// 排除loopback類型地址 if (inetAddr.isSiteLocalAddress()) { // 如果是site-local地址,就是它了 return inetAddr; } else if (candidateAddress == null) { // site-local類型的地址未被發現,先記錄候選地址 candidateAddress = inetAddr; } } } } if (candidateAddress != null) { return candidateAddress; } // 如果沒有發現 non-loopback地址.只能用最次選的方案 InetAddress jdkSuppliedAddress = InetAddress.getLocalHost(); return jdkSuppliedAddress; } catch (Exception e) { e.printStackTrace(); } return null; } } 2.本地的ip地址: