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; 
           }
    }
  • 相关阅读:
    [代码质量] Git统计本次提交新增代码行数,建议每个评审commit新增行数小于400行
    [Web 安全] WASC 和 OWASP两个web安全方面组织机构介绍
    [web 前端] Npm package.json与package-lock.json文件的作用
    Mac IDEA 插件 lombok
    IDEA 导入新的项目步骤
    IDEA for Mac 快捷键
    Flink --- hello world
    LogisticRegression回归算法 Sklearn 参数详解
    keep going
    在 macOS 上快速新建 txt 文本文件
  • 原文地址:https://www.cnblogs.com/sinosoft/p/13902106.html
Copyright © 2011-2022 走看看