Linux和Windows/k8s/nginx获取本机iP地址

获得本机的操作系统及ip

  public static void main(String[] args) {
    System.out.println(getLocalIP());
  }

  /**
   * 获得本机操作系统
   *
   * @return String
   */
  public static boolean isWindowsOS() {
    boolean isWindowsOS = false;
    String osName = System.getProperty("os.name");
    if (osName.toLowerCase().indexOf("windows") > -1) {
      isWindowsOS = true;
    }
    return isWindowsOS;
  }

  /**
   * 获取本机ip地址,并自动区分Windows还是linux操作系统
   *
   * @return String
   */
  public static String getLocalIP() {
    String sIP = "";
    InetAddress ip = null;
    try {
      //如果是Windows操作系统
      if (isWindowsOS()) {
        ip = InetAddress.getLocalHost();
      }
      //如果是Linux操作系统
      else {
        boolean bFindIP = false;
        Enumeration<NetworkInterface> netInterfaces = (Enumeration<NetworkInterface>) NetworkInterface
                .getNetworkInterfaces();
        while (netInterfaces.hasMoreElements()) {
          if (bFindIP) {
            break;
          }
          NetworkInterface ni = (NetworkInterface) netInterfaces.nextElement();
          //----------特定情况,可以考虑用ni.getName判断
          //遍历所有ip
          Enumeration<InetAddress> ips = ni.getInetAddresses();
          while (ips.hasMoreElements()) {
            ip = (InetAddress) ips.nextElement();
            if (ip.isSiteLocalAddress()
                    && !ip.isLoopbackAddress()   //127.开头的都是lookback地址
                    && ip.getHostAddress().indexOf(":") == -1) {
              bFindIP = true;
              break;
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    if (null != ip) {
      sIP = ip.getHostAddress();
    }
    return sIP;
  }

获得request请求的ip/浏览器信息/操作系统/ip所在城市等信息

package com.genertech.plm.aia.login.util;

/**
 * @author evanli
 * @version V1.0
 * @date 2020-11-25 18:37:57
 * @desc ip工具类
 */

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;


/**
 * Ip地址
 */
public class IpUtil {
  private static Logger logger = LoggerFactory.getLogger(IpUtil.class);
  private static final String IP_UTILS_FLAG = ",";
  private static final String UNKNOWN = "unknown";
  private static final String LOCALHOST_IP = "0:0:0:0:0:0:0:1";
  private static final String LOCALHOST_IP1 = "127.0.0.1";

  /**
   * 获取IP地址
   * <p>
   * 使用Nginx等反向代理软件,则不能通过request.getRemoteAddr()获取IP地址
   * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
   */
  public static String getIpAddr(HttpServletRequest request) {
    String ip = null;
    try {
      //以下两个获取在k8s中,将真实的客户端IP,放到了x-Original-Forwarded-For。而将WAF的回源地址放到了 x-Forwarded-For了。
      ip = request.getHeader("X-Original-Forwarded-For");
      if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("X-Forwarded-For");
      }
      //获取nginx等代理的ip
      if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("x-forwarded-for");
      }
      if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("Proxy-Client-IP");
      }
      if (StringUtils.isEmpty(ip) || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("WL-Proxy-Client-IP");
      }
      if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_CLIENT_IP");
      }
      if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getHeader("HTTP_X_FORWARDED_FOR");
      }
      //兼容k8s集群获取ip
      if (StringUtils.isEmpty(ip) || UNKNOWN.equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
        if (LOCALHOST_IP1.equalsIgnoreCase(ip) || LOCALHOST_IP.equalsIgnoreCase(ip)) {
          //根据网卡取本机配置的IP
          InetAddress iNet = null;
          try {
            iNet = InetAddress.getLocalHost();
          } catch (UnknownHostException e) {
            logger.error("getClientIp error: {}", e);
          }
          ip = iNet.getHostAddress();
        }
      }
    } catch (Exception e) {
      logger.error("IPUtils ERROR ", e);
    }
    //使用代理,则获取第一个IP地址
    if (!StringUtils.isEmpty(ip) && ip.indexOf(IP_UTILS_FLAG) > 0) {
      ip = ip.substring(0, ip.indexOf(IP_UTILS_FLAG));
    }

    return ip;
  }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值