当前位置:   article > 正文

SpringBoot获取用户的ip地址信息_op.sethostname(iputil.getuseragent());

op.sethostname(iputil.getuseragent());

前言

        在SpringBoot应用程序中,获取用户的IP地址信息是常见需求。通过分析请求头中的"X-Forwarded-For"字段,可以获取到真实的客户端IP地址。这对于日志记录、流量分析以及安全审计等场景非常有用。

一、IP工具类

  1. @Slf4j
  2. @Component
  3. public class IpUtil {
  4. private static DbSearcher searcher;
  5. private static Method method;
  6. public static String getIpAddress(HttpServletRequest request) {
  7. String ipAddress = request.getHeader("X-Real-IP");
  8. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  9. ipAddress = request.getHeader("x-forwarded-for");
  10. }
  11. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  12. ipAddress = request.getHeader("Proxy-Client-IP");
  13. }
  14. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  15. ipAddress = request.getHeader("WL-Proxy-Client-IP");
  16. }
  17. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  18. ipAddress = request.getHeader("HTTP_CLIENT_IP");
  19. }
  20. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  21. ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
  22. }
  23. if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
  24. ipAddress = request.getRemoteAddr();
  25. if ("127.0.0.1".equals(ipAddress) || "0:0:0:0:0:0:0:1".equals(ipAddress)) {
  26. //根据网卡取本机配置的IP
  27. InetAddress inet = null;
  28. try {
  29. inet = InetAddress.getLocalHost();
  30. } catch (UnknownHostException e) {
  31. log.error("getIpAddress exception:", e);
  32. }
  33. assert inet != null;
  34. ipAddress = inet.getHostAddress();
  35. }
  36. }
  37. log.info("ip:{}",ipAddress);
  38. return ipAddress;
  39. // return StringUtils.substringBefore(ipAddress, ",");
  40. }
  41. @PostConstruct
  42. private void initIp2regionResource() throws Exception {
  43. InputStream inputStream = new ClassPathResource("/ip/ip2region.db").getInputStream();
  44. byte[] dbBinStr = FileCopyUtils.copyToByteArray(inputStream);
  45. DbConfig dbConfig = new DbConfig();
  46. searcher = new DbSearcher(dbConfig, dbBinStr);
  47. method = searcher.getClass().getMethod("memorySearch", String.class);
  48. }
  49. public static String getIpSource(String ipAddress) {
  50. if (ipAddress == null || !Util.isIpAddress(ipAddress)) {
  51. log.error("Error: Invalid ip address");
  52. return "";
  53. }
  54. try {
  55. DataBlock dataBlock = (DataBlock) method.invoke(searcher, ipAddress);
  56. String ipInfo = dataBlock.getRegion();
  57. if (!StringUtils.isEmpty(ipInfo)) {
  58. ipInfo = ipInfo.replace("|0", "");
  59. ipInfo = ipInfo.replace("0|", "");
  60. return ipInfo;
  61. }
  62. } catch (Exception e) {
  63. log.error("getCityInfo exception:", e);
  64. }
  65. return "";
  66. }
  67. public static String getIpProvince(String ipSource) {
  68. String[] strings = ipSource.split("\\|");
  69. if (strings[1].endsWith("省")) {
  70. return StringUtils.substringBefore(strings[1], "省");
  71. }
  72. return strings[1];
  73. }
  74. public static UserAgent getUserAgent(HttpServletRequest request) {
  75. return UserAgent.parseUserAgentString(request.getHeader("User-Agent"));
  76. }
  77. }

二、ip2region.db文件(百度网盘下载)

链接:https://pan.baidu.com/s/1-99YdE1e92Z5t-_h7mB6xg 
提取码:31fv

三、使用示例

  1. @Autowired
  2. private HttpServletRequest request;
  3. @Test
  4. public void getUserIp() {
  5. //ip
  6. String ipAddress = IpUtil.getIpAddress(request);
  7. //来源
  8. String ipSource = IpUtil.getIpSource(ipAddress);
  9. UserAgent userAgent = IpUtil.getUserAgent(request);
  10. //获取浏览器名称
  11. String browser = userAgent.getBrowser().getName();
  12. //操作系统
  13. String os = userAgent.getOperatingSystem().getName();
  14. }

四、结束语

        需要注意的是,如果用户通过代理服务器访问应用程序,则"X-Forwarded-For"字段可能包含多个IP地址,需要结合其他因素来判断最接近客户端的真实IP地址。同时,为了保护用户隐私和安全,获取IP地址时应遵循相关法律法规和隐私政策。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/405775
推荐阅读
相关标签
  

闽ICP备14008679号