Java 获取本机、Linux IP地址工具类
import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.UnknownHostException; import java.util.Enumeration; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.tools.zip.ZipEntry; import org.apache.tools.zip.ZipFile; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class CommonIpUtil { private static Log log = LogFactory.getLog(CommonUtil.class); private static final Logger logger = LoggerFactory.getLogger(CommonUtil.class); public static String getIpAddress() throws UnknownHostException{ InetAddress address = InetAddress.getLocalHost(); String ipAddress = address.getHostAddress(); if(ipAddress != null && !"".equals(ipAddress) && !"127.0.0.1".equals(ipAddress)){ log.info("InetAddress.getLocalHost().getHostAddress():"+ipAddress); return ipAddress; } //linux环境下需要以下步骤才能获取到 Enumeration allNetInterfaces = null; try { allNetInterfaces = NetworkInterface.getNetworkInterfaces(); } catch (java.net.SocketException e) { logger.error("getIpAddress 异常:", e); } InetAddress ip = null; while (allNetInterfaces.hasMoreElements()) { NetworkInterface netInterface = (NetworkInterface) allNetInterfaces .nextElement(); Enumeration addresses = netInterface.getInetAddresses(); while (addresses.hasMoreElements()) { ip = (InetAddress) addresses.nextElement(); if (ip != null && ip instanceof InetAddress) { if(!"127.0.0.1".equals(ip.getHostAddress()) && ".".indexOf(ip.getHostAddress()) > -1){ ipAddress = ip.getHostAddress(); } } } } log.info("NetworkInterface.getHostAddress():"+ipAddress); return ipAddress; } }