当前位置: 首页 > 工具软件 > iputils > 使用案例 >

IPUtils 获取IP工具类

轩辕华辉
2023-12-01
IPUtils 获取IP工具类
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;
public class IPUtils {
   /**
    * 获取IP地址
    *
    * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
    * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
    */
   public static String getIpAddr(HttpServletRequest request) {
       String ip = null;
        try {
            ip = request.getHeader("x-forwarded-for");
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } catch (Exception e) {
           log.error("IPUtils ERROR ", e);
        }

        //使用代理,则获取第一个IP地址
        if(StringUtils.isBlank(ip) && ip.length() > 15) {
         if(ip.indexOf(",") > 0) {
            ip = ip.substring(0, ip.indexOf(","));
         }
      }

        return ip;
    }

    /**
     * @description 获取系统环境ip
     */
    public static String getCurrentSystemIp() {
        try {
            Enumeration<NetworkInterface> networkInterfaces = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaces.hasMoreElements()) {
                NetworkInterface ni =  networkInterfaces.nextElement();
                Enumeration<InetAddress> nias = ni.getInetAddresses();
                while (nias.hasMoreElements()) {
                    InetAddress ia = nias.nextElement();
                    if (!ia.isLinkLocalAddress() && !ia.isLoopbackAddress() && ia instanceof Inet4Address) {
                        return ia.toString().substring(1);
                    }
                }
            }
        } catch (SocketException e) {
            log.error("Failed to get current system Ip ", e);
        }
        return null;
    }
 类似资料: