java使用IpUtil获取真实ip地址
2 3 import org.apache.commons.lang3.text.StrTokenizer; 4 5 import javax.servlet.http.HttpServletRequest; 6 import java.util.regex.Pattern; 7 8 /** 9 * IpV4 获取真实ip地址 10 */ 11 public class IpUtil { 12 13 public static final String _255 = "(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)"; 14 public static final Pattern pattern = Pattern.compile("^(?:" + _255 + "\\.){3}" + _255 + "$"); 15 16 /** 17 * String类型ip转为Long类型 18 * 19 * @param longIp 20 * @return String 21 */ 22 public static String longToIpV4(long longIp) { 23 int octet3 = (int) ((longIp >> 24) % 256); 24 int octet2 = (int) ((longIp >> 16) % 256); 25 int octet1 = (int) ((longIp >> 8) % 256); 26 int octet0 = (int) ((longIp) % 256); 27 return octet3 + "." + octet2 + "." + octet1 + "." + octet0; 28 } 29 30 /** 31 * Long类型ip转为String类型 32 * 33 * @param longIp 34 * @return Long 35 */ 36 public static long ipV4ToLong(String ip) { 37 String[] octets = ip.split("\\."); 38 return (Long.parseLong(octets[0]) << 24) + (Integer.parseInt(octets[1]) << 16) 39 + (Integer.parseInt(octets[2]) << 8) + Integer.parseInt(octets[3]); 40 } 41 42 /** 43 * @param ip 44 * @return boolean 45 */ 46 public static boolean isIPv4Private(String ip) { 47 long longIp = ipV4ToLong(ip); 48 return (longIp >= ipV4ToLong("10.0.0.0") && longIp <= ipV4ToLong("10.255.255.255")) 49 || (longIp >= ipV4ToLong("172.16.0.0") && longIp <= ipV4ToLong("172.31.255.255")) 50 || longIp >= ipV4ToLong("192.168.0.0") && longIp <= ipV4ToLong("192.168.255.255"); 51 } 52 53 public static boolean isIPv4Valid(String ip) { 54 return pattern.matcher(ip).matches(); 55 } 56 57 /** 58 * 获取String类型真实ip地址,基于反向代理。 59 * 60 * @param request 61 * @return 62 * 在反向代理中将X-Forward-For替换为remote_addr,即,真实的IP地址。 63 */ 64 public static String getIpFromRequest(HttpServletRequest request) { 65 String ip; 66 boolean found = false; 67 if ((ip = request.getHeader("x-forwarded-for")) != null) { 68 StrTokenizer tokenizer = new StrTokenizer(ip, ","); 69 while (tokenizer.hasNext()) { 70 ip = tokenizer.nextToken().trim(); 71 if (isIPv4Valid(ip) && !isIPv4Private(ip)) { 72 found = true; 73 break; 74 } 75 } 76 } 77 if (!found) { 78 ip = request.getRemoteAddr();// 获得ip地址 79 } 80 return ip; 81 } 82 }