| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- package com.fdkankan.ucenter.geo;
- import javax.servlet.http.HttpServletRequest;
- import java.util.HashMap;
- import java.util.Map;
- public class IPUtils {
- private static IPLocationService locationService;
- static {
- try {
- locationService = new IPLocationService("geo/GeoLite2-City.mmdb");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- public static String getCountry(String ip) {
- if (locationService != null) {
- return locationService.getCountryByIP(ip);
- }
- return "Unknown";
- }
- public static Map<String, String> getLocationInfo(String ip) {
- Map<String, String> info = new HashMap<>();
- if (locationService != null) {
- IPLocation location = locationService.getLocationByIP(ip);
- if (location != null) {
- info.put("country", location.getCountry());
- info.put("city", location.getCity());
- info.put("latitude", String.valueOf(location.getLatitude()));
- info.put("longitude", String.valueOf(location.getLongitude()));
- }
- }
- return info;
- }
- public static String getIpAddr(HttpServletRequest request) {
- String ipAddress = null;
- 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();
- }
- // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
- if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
- // = 15
- if (ipAddress.indexOf(",") > 0) {
- ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
- }
- }
- // 或者这样也行,对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
- //return ipAddress!=null&&!"".equals(ipAddress)?ipAddress.split(",")[0]:null;
- return ipAddress;
- }
- }
|