diff --git a/src/main/java/com/lq/code/util/os/NetUtil.java b/src/main/java/com/lq/code/util/os/NetUtil.java index be79760..337bb87 100755 --- a/src/main/java/com/lq/code/util/os/NetUtil.java +++ b/src/main/java/com/lq/code/util/os/NetUtil.java @@ -1,13 +1,21 @@ package com.lq.code.util.os; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + import java.net.InetAddress; +import java.net.NetworkInterface; +import java.net.SocketException; import java.net.UnknownHostException; +import java.util.Enumeration; /** 获取计算机网络信息 * Created by qi_liang on 2018/6/9. */ public class NetUtil { + public static final Logger LOGGER = LoggerFactory.getLogger(NetUtil.class); + public static String getIP(){ String ip = null; try { @@ -20,4 +28,31 @@ public class NetUtil { return ip; } + public static String getLocalIpAddr(){ + Enumeration networks = null; + try { + // 获取网卡设备 + networks = NetworkInterface.getNetworkInterfaces(); + } catch (SocketException e) { + LOGGER.info(e.getMessage()); + } + InetAddress ip = null; + Enumeration addrs; + // 遍历网卡设备 + while (networks.hasMoreElements()){ + addrs = networks.nextElement().getInetAddresses(); + while (addrs.hasMoreElements()){ + ip = addrs.nextElement(); + if (ip != null && ip instanceof InetAddress && ip.isSiteLocalAddress()){ + if (ip.getHostAddress()==null || "".equals(ip.getHostAddress())){ + LOGGER.info("获取到的客户端内网ip为空,从配置文件读取本地ip。"); + return null; + } + return ip.getHostAddress();// 客户端ip + } + } + } + return null; + } + }