1. 程式人生 > >IP工具類

IP工具類

trace pre except PE import 但是 private proxy 獲取

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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

/**
 * 獲取IP工具類
 * @create 2017-03-29
 */
public class IPUtils {
    private static Logger logger = LoggerFactory.getLogger(IPUtils.class
); private static String LOCAL_IP_STAR_STR = "192.168."; static { String ip = null; String hostName = null; try { hostName = InetAddress.getLocalHost().getHostName(); InetAddress ipAddr[] = InetAddress.getAllByName(hostName); for (int
i = 0; i < ipAddr.length; i++) { ip = ipAddr[i].getHostAddress(); if (ip.startsWith(LOCAL_IP_STAR_STR)) { break; } } if (ip == null) { ip = ipAddr[0].getHostAddress(); } }
catch (UnknownHostException e) { logger.error("IpHelper error."); e.printStackTrace(); } LOCAL_IP = ip; HOST_NAME = hostName; } /** * 系統的本地IP地址 */ public static final String LOCAL_IP; /** * 系統的本地服務器名 */ public static final String HOST_NAME; /** * <p> * 獲取客戶端的IP地址的方法是:request.getRemoteAddr(),這種方法在大部分情況下都是有效的。 * 但是在通過了Apache,Squid等反向代理軟件就不能獲取到客戶端的真實IP地址了,如果通過了多級反向代理的話, * X-Forwarded-For的值並不止一個,而是一串IP值, 究竟哪個才是真正的用戶端的真實IP呢? * 答案是取X-Forwarded-For中第一個非unknown的有效IP字符串。 * 例如:X-Forwarded-For:192.168.1.110, 192.168.1.120, * 192.168.1.130, 192.168.1.100 用戶真實IP為: 192.168.1.110 * </p> * * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { String ip = request.getHeader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("WL-Proxy-Client-IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_CLIENT_IP"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getHeader("HTTP_X_FORWARDED_FOR"); } if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) { ip = request.getRemoteAddr(); if (ip.equals("127.0.0.1")) { /** 根據網卡取本機配置的IP */ InetAddress inet = null; try { inet = InetAddress.getLocalHost(); ip = inet.getHostAddress(); } catch (UnknownHostException e) { logger.error("IpHelper error." + e.toString()); } } } /** * 對於通過多個代理的情況, 第一個IP為客戶端真實IP,多個IP按照‘,‘分割 "***.***.***.***".length() = * 15 */ if (ip != null && ip.length() > 15) { if (ip.indexOf(",") > 0) { ip = ip.substring(0, ip.indexOf(",")); } } return ip; } }

IP工具類