IPUtils.java 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.fdkankan.ucenter.geo;
  2. import javax.servlet.http.HttpServletRequest;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. public class IPUtils {
  6. private static IPLocationService locationService;
  7. static {
  8. try {
  9. locationService = new IPLocationService("geo/GeoLite2-City.mmdb");
  10. } catch (Exception e) {
  11. e.printStackTrace();
  12. }
  13. }
  14. public static String getCountry(String ip) {
  15. if (locationService != null) {
  16. return locationService.getCountryByIP(ip);
  17. }
  18. return "Unknown";
  19. }
  20. public static Map<String, String> getLocationInfo(String ip) {
  21. Map<String, String> info = new HashMap<>();
  22. if (locationService != null) {
  23. IPLocation location = locationService.getLocationByIP(ip);
  24. if (location != null) {
  25. info.put("country", location.getCountry());
  26. info.put("city", location.getCity());
  27. info.put("latitude", String.valueOf(location.getLatitude()));
  28. info.put("longitude", String.valueOf(location.getLongitude()));
  29. }
  30. }
  31. return info;
  32. }
  33. public static String getIpAddr(HttpServletRequest request) {
  34. String ipAddress = null;
  35. ipAddress = request.getHeader("x-forwarded-for");
  36. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  37. ipAddress = request.getHeader("Proxy-Client-IP");
  38. }
  39. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  40. ipAddress = request.getHeader("WL-Proxy-Client-IP");
  41. }
  42. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  43. ipAddress = request.getRemoteAddr();
  44. }
  45. // 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  46. if (ipAddress != null && ipAddress.length() > 15) { // "***.***.***.***".length()
  47. // = 15
  48. if (ipAddress.indexOf(",") > 0) {
  49. ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
  50. }
  51. }
  52. // 或者这样也行,对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
  53. //return ipAddress!=null&&!"".equals(ipAddress)?ipAddress.split(",")[0]:null;
  54. return ipAddress;
  55. }
  56. }