简写版本
package com.gblfy.util;import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;/*** 获取本地ip地址 适用于Windowds和Linux*/
public class WebToolUtils {/*** 获取本地ip地址*** @return*/public static String getInet4Address() {Enumeration<NetworkInterface> nis;String ip = null;try {nis = NetworkInterface.getNetworkInterfaces();for (; nis.hasMoreElements();) {NetworkInterface ni = nis.nextElement();Enumeration<InetAddress> ias = ni.getInetAddresses();for (; ias.hasMoreElements();) {InetAddress ia = ias.nextElement();if (ia instanceof Inet4Address && !ia.getHostAddress().equals("127.0.0.1")) {ip = ia.getHostAddress();}}}} catch (SocketException e) {e.printStackTrace();}return ip;}public static void main(String[] args)throws Exception {String localIP = getInet4Address();System.out.println("获取本地ip地址:---------------------"+localIP);}
}
未优化版本
package com.gblfy.config;import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;@Controller
public class AbController {@ResponseBody@RequestMapping(value = "/Testone", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")public static String Testone() throws Exception {String ip = "";try {for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {NetworkInterface intf = en.nextElement();String name = intf.getName();if (!name.contains("docker") && !name.contains("lo")) {for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {InetAddress inetAddress = enumIpAddr.nextElement();if (!inetAddress.isLoopbackAddress()) {String ipaddress = inetAddress.getHostAddress().toString();if (!ipaddress.contains("::") && !ipaddress.contains("0:0:") && !ipaddress.contains("fe80")) {ip = ipaddress;System.out.println(ipaddress);}}}}}} catch (SocketException ex) {System.out.println("获取ip地址异常");ip = "127.0.0.1";ex.printStackTrace();}System.out.println("IP:"+ip);return ip;}public static void main(String[] args) throws Exception {String testone = Testone();System.out.println("eilvlhwlhevihei"+testone);}
}