获取客户端真实IP地址

java

浏览数:350

2019-1-12

AD:资源代下载服务


获取客户端真实IP地址

import javax.servlet.http.HttpServletRequest;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.util.*;

/**
 * IP工具类
 */
public class IPUtil {

    private static final String IP_SEPARATOR = ",";

    /**
     * 服务器端获取客户端真实的IP地址
     * 如果使用的是Druid连接池,可以参考使用:
     * com.alibaba.druid.util.DruidWebUtils#getRemoteAddr方法,
     * 但这个是经过多级代理的IP地址,需要自己处理下获取第一个。
     * @param request
     * @return
     */
    public static String getIpAddress(HttpServletRequest request) {
        String ip = request.getHeader("X-FORWARDED-FOR ");
        if (ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("HTTPCLIENTIP");
        }
        if (ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }
        if (ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr ();
        }
        if (ip.contains(IP_SEPARATOR)){
            return ip.split(IP_SEPARATOR)[0];
        }else{
            return ip;
        }
    }

    /**
     * 获取当前机器的所有IP
     * @return
     */
    public static String[] getIps() {
        List<String> ips = new ArrayList<>();
        try{
            Enumeration<NetworkInterface> nets = NetworkInterface.getNetworkInterfaces();
            for (NetworkInterface netint:Collections.list(nets)) {
                List<InterfaceAddress> list = netint.getInterfaceAddresses();
                for (InterfaceAddress interfaceAddress : list) {
                    String localIp = interfaceAddress.getAddress().getHostAddress();
                    if (localIp != null && !"".equals(localIp)) {
                        ips.add(localIp);
                    }
                }
            }
        }catch (Exception e){
            return null;
        }
        return ips.toArray(new String[ips.size()]);
    }

    public static void main(String[] args) {
        String[] ips = getIps();
        for (String ip : ips){
            System.out.println(ip);
        }
    }

}