zoukankan      html  css  js  c++  java
  • 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; 
           }
    }
  • 相关阅读:
    AWS Redshift 采坑记
    EF Core 小工具
    Setup .net core EF
    Bat 使用MSBuild 制作发布包 (更新20180713)
    Https web Api 拉取数据踩坑记录
    C# 后台程序 通过批处理进行监控
    C#计算日期步进
    IIS 预热 (8.0及8.0以上版本)
    MSBuild 执行文档,关于使用命令行编译
    基于Bamboo的CI配置汇总(.Net Web及Api)
  • 原文地址:https://www.cnblogs.com/sinosoft/p/13902106.html
Copyright © 2011-2022 走看看