【RestController】Restful接口获取请求者IP地址

虽然是老生常谈了,但有其用途,可以记在这。

函数及使用干脆一起列出来:

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class JsonCtrl {

    @RequestMapping(value="/sampleInterface01", method=RequestMethod.GET)
    public Map<String,String> getSample(HttpServletRequest rqst) {
        Map<String,String> map=new LinkedHashMap<>();
        map.put("湖南", "岳阳");
        map.put("辽宁", "大连");
        map.put("time", LocalDate.now()+" "+LocalTime.now());
        map.put("visitor Ip", getIp(rqst));
        
        return map;
    }
    
    /**
     * 取得访问者IP
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根据网卡取本机配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress="";
        }
        // ipAddress = this.getRequest().getRemoteAddr();
 
        return ipAddress;
    }
}

从其它机器访问的效果:

 由此可以看出此方法是可行的。

本机访问则是:

 

 

0:0:0:0:0:0:0:1 的结果应是环回地址的缘故。
END
原文地址:https://www.cnblogs.com/heyang78/p/15487688.html