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; 
           }
    }
  • 相关阅读:
    flask 返回json数据
    flask 中文乱码
    flask 参数校验
    AOP集成防止连续多次点击问题
    关于横竖屏切换导致的Activity重建问题
    Flutter工程无法找到Android真机或Android模拟器
    Failed to find configured root that contains
    Unable to resolve dependency问题解决
    双重ScrollView,RecyclerView联动实例
    RecyclerView联动滑动失败
  • 原文地址:https://www.cnblogs.com/sinosoft/p/13902106.html
Copyright © 2011-2022 走看看