request获取请求客户端ip或服务器ip以及请求ip

1.项目需求

根据用户请求过来的ip来判断是内网选择内网上传方式,是外网选择外网上传方式

2.代码分析

  jsonObject.put("playUrl1", request.getRemoteAddr());
  jsonObject.put("playUrl2", request.getServerName());
  jsonObject.put("playUrl3", request.getRequestURL());
  jsonObject.put("playUrl4", request.getRequestURI());
  jsonObject.put("playUrl5", request.getServerPort());//得到请求的端口7080

得到的结果:
request获取请求客户端ip或服务器ip以及请求ip_第1张图片

3.上获取ip工具类

IpUtil :

package com.hst.ces.meetingresource.util;

import com.hst.ces.base.util.HttpServletUtil;
import lombok.SneakyThrows;
import org.apache.commons.lang3.text.StrTokenizer;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @author chenhuanwei
 * @date 2019/12/4
 */
public class IpUtil {

    private static final Set<String> LOCALHOST_SET = Stream
            .of("127.0.0.1", "LOCALHOST", "0:0:0:0:0:0:0:1")
            .collect(Collectors.toSet());


    private static final String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";
    private static final Pattern pattern = Pattern.compile("^(?:" + _255 + "\\.){3}" + _255 + "$");

    /**
     * 获取客户端IP
     */
    public static String getIpFromRequest() {
        return getIpFromRequest(HttpServletUtil.getRequest());
    }


    /**
     * 获取客户端IP
     */
    public static String getIpFromRequest(HttpServletRequest request) {
        String ip;
        boolean found = false;
        if ((ip = request.getHeader("x-forwarded-for")) != null) {
            StrTokenizer tokenizer = new StrTokenizer(ip, ",");
            while (tokenizer.hasNext()) {
                ip = tokenizer.nextToken().trim();
                if (isIPv4Valid(ip) && !isIPv4Private(ip)) {
                    found = true;
                    break;
                }
            }
        }
        if (!found) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

    private static String longToIpV4(long longIp) {
        int octet3 = (int) ((longIp >> 24) % 256);
        int octet2 = (int) ((longIp >> 16) % 256);
        int octet1 = (int) ((longIp >> 8) % 256);
        int octet0 = (int) ((longIp) % 256);
        return octet3 + "." + octet2 + "." + octet1 + "." + octet0;
    }

    private static long ipV4ToLong(String ip) {
        String[] octets = ip.split("\\.");
        return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16)
                + (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]);
    }

    private static boolean isIPv4Private(String ip) {
        long longIp = ipV4ToLong(ip);
        return (longIp >= ipV4ToLong("10.0.0.0") && longIp <= ipV4ToLong("10.255.255.255"))
                || (longIp >= ipV4ToLong("172.16.0.0") && longIp <= ipV4ToLong("172.31.255.255"))
                || longIp >= ipV4ToLong("192.168.0.0") && longIp <= ipV4ToLong("192.168.255.255");
    }

    private static boolean isIPv4Valid(String ip) {
        return pattern.matcher(ip).matches();
    }


    /**
     * 获取服务器IP
     */
    public static String getIpAddress() {
        return getIpAddress(HttpServletUtil.getRequest());
    }

    /**
     * 获取服务器IP
     * 访问方式有localhost、127.0.0.1、本地IP、映射IP
     */
    @SneakyThrows
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getServerName();
        if (LOCALHOST_SET.contains(ip.toUpperCase())) {
            ip = getIpFromRequest(request);
        }
        return ip;
    }
}

HttpServletUtil :

package com.hst.ces.base.util;

import com.hst.ces.base.constant.CacheConstant;
import com.hst.ces.base.constant.CommonConst;
import com.hst.ces.base.constant.DevInfoConst;
import com.hst.ces.base.entity.UserInfo;
import com.hst.ces.cache.HstCache;
import com.hst.ces.toolkit.net.IpUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author SunYang
 * @version 1.0
 * @description: 为MVC业务流程中提供静态方式访问request, response内容
 * @date 2021/01/18 11:20
 */
public class HttpServletUtil {

    private HttpServletUtil() {
    }

    /**
     * description: 静态获取request对象
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        ServletRequestAttributes servletRequestAttributes =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletRequestAttributes == null ? null : servletRequestAttributes.getRequest();
    }

    /**
     * description: 静态获取response 对象
     *
     * @return HttpServletResponse
     */
    public static HttpServletResponse getResponse() {
        ServletRequestAttributes servletWebRequest =
                (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return servletWebRequest == null ? null : servletWebRequest.getResponse();
    }


    /**
     * 获取当前请求用户对象
     *
     * @return UserInfo
     */
    public static UserInfo getUserInfo() {
        HttpServletRequest request = getRequest();
        return request == null ? null : (UserInfo) request.getAttribute("user");
    }

    /**
     * 获取当前请求的域名(ip)+端口
     */
    public static String getDomain() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        return request.getRequestURL().toString().replaceAll(request.getRequestURI(), "");
    }

    /**
     * 试图获取用户请求域名地址
     *
     * @return 网址
     */
    public static String getHost() {
        String serverName = null;
        HttpServletRequest request = getRequest();
        if (request != null) {
            serverName = request.getServerName();
        }
        if (IpUtil.isLocalHost(serverName)) {
            serverName = IpUtil.getIpAddress();
        }
        return serverName;
    }

    /**
     * 获取容器ContextPath
     */
    public static String getCtxPath() {
        HttpServletRequest request = getRequest();
        assert request != null;
        return request.getContextPath();
    }


    public static String getWebMapPort(String sysParamAddressName) {
        HttpServletRequest request = getRequest();
        String serverName = request.getServerName();
        String port = "";
        String address = HstCache.getString(HstCache.SYSTEM,
                                                  CacheConstant.SYS_PARAM_PREFIX + sysParamAddressName);
        if (StringUtils.isNotBlank(address)) {
            String[] addr = address.split(CommonConst.SEMICOLON);
            for (int i = 0; i < addr.length; i++) {
                String[] ipo = addr[i].split(CommonConst.COLON);
                if (ipo[0].equals(serverName)){
                    port = ipo[1];
                    break;
                }
            }
        }
        return port;
    }

    /**
     * 试图拼装出本服务的可请求网址
     * @mapPort 映射端口 可为空
     * @return 网站地址
     */
    public static String getWebSite() {
        HttpServletRequest request = getRequest();
        String serverName = null;
        if (request != null) {
            serverName = request.getServerName();
        }
        if (serverName == null || IpUtil.isLocalHost(serverName)) {
            serverName = IpUtil.getIpAddress();
        }
        if (request == null) {
            return "";
        }
        String scheme = request.getScheme();
        String mapPort;
        if (scheme.equalsIgnoreCase(CommonConst.HTTPS)) {
            mapPort = getWebMapPort(DevInfoConst.CONF_ADDRESS);
        } else {
            mapPort = getWebMapPort(DevInfoConst.CONF_ADDRESS_HTTP);
        }
        String port = StringUtils.isBlank(mapPort) ? String.valueOf(request.getServerPort()) : mapPort;
        return scheme + "://" + serverName + ":" + port + request.getContextPath();
    }

    /**
     * 获取request中的token
     */
    public static String getToken() {
        HttpServletRequest request = getRequest();
        if (request == null) {
            return null;
        }
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)) {
            token = request.getParameter("token");
        }
        return token;
    }

}

你可能感兴趣的:(Java,+,JVM,+,Tomcat,服务器,tcp/ip,http)