Java 怎么从httpservletrequest获取客户端IP

2019年8月17日22:03:12Java 怎么从httpservletrequest获取客户端IP已关闭评论 846 547字阅读1分49秒

1.简介

Java 怎么从httpservletrequest获取客户端IP?——请看下文。

2.示例代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import javax.servlet.http.HttpServletRequest;

public class Main{
    public static String getClientIP(HttpServletRequest request) {
        String ip;
        ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0) {
            ip = request.getHeader("http-x-forwarded-for");
            if (ip == null || ip.length() == 0) {
                ip = request.getHeader("remote-addr");
                if (ip == null || ip.length() == 0) {
                    ip = request.getRemoteAddr();
                }
            }
        }
        return ip;
    }
}

 
编程十万个怎么办