当前位置:   article > 正文

Java 根据IP获取IP地址信息(离线)

Java 根据IP获取IP地址信息(离线)
  1. <!-- https://mvnrepository.com/artifact/org.lionsoul/ip2region -->
  2. <dependency>
  3. <groupId>org.lionsoul</groupId>
  4. <artifactId>ip2region</artifactId>
  5. <version>2.7.0</version>
  6. </dependency>

地址:https://gitcode.com/lionsoul2014/ip2region/overview

数据文件下载下来放到resources:

  1. public class IPUtil {
  2. /**
  3. * 将整个xdb文件加载到内存中
  4. */
  5. private final static Searcher SEARCHER;
  6. static {
  7. try {
  8. ClassPathResource resource = new ClassPathResource("ip2region.xdb");
  9. String path = resource.getURL().getPath();
  10. byte[] cBuff = Searcher.loadContentFromFile(path);
  11. SEARCHER = Searcher.newWithBuffer(cBuff);
  12. } catch (Exception e) {
  13. throw new RuntimeException("初始化ip2region.xdb异常!");
  14. }
  15. }
  16. /**
  17. * @Description 获取ip地址信息
  18. * @param ipStr 192.168.0.1
  19. * @Throws
  20. * @Return java.util.List<java.lang.String> 返回结果形式(国家|区域|省份|城市|ISP)
  21. * @Date 2024-03-08 17:43:45
  22. * @Author WangKun
  23. */
  24. public static List<String> getIpAddress(String ipStr) {
  25. return getIpAddress(ipStr, null);
  26. }
  27. /**
  28. * @Description 获取ip地址信息
  29. * @param ipStr ip 经过转换后的
  30. * @param index
  31. * @Throws
  32. * @Return java.util.List<java.lang.String>
  33. * @Date 2024-03-08 17:43:51
  34. * @Author WangKun
  35. */
  36. public static List<String> getIpAddress(String ipStr, int[] index) {
  37. try {
  38. long ip = Searcher.checkIP(ipStr);
  39. return getIpAddress(ip, index);
  40. } catch (Exception e) {
  41. throw new RuntimeException("ip解析为long系统异常!");
  42. }
  43. }
  44. /**
  45. * @Description 获取ip地址信息
  46. * @param ip
  47. * @param index
  48. * @Throws
  49. * @Return java.util.List<java.lang.String>
  50. * @Date 2024-03-08 17:43:55
  51. * @Author WangKun
  52. */
  53. public static List<String> getIpAddress(Long ip, int[] index) {
  54. //获取xdb文件资源
  55. List<String> regionList = new ArrayList<>();
  56. try {
  57. String region = SEARCHER.search(ip);
  58. String[] split = region.split("\\|");
  59. if (index == null) {
  60. regionList = Arrays.asList(split);
  61. } else {
  62. for (int i : index) {
  63. regionList.add(split[i]);
  64. }
  65. }
  66. //关闭资源
  67. SEARCHER.close();
  68. } catch (Exception e) {
  69. throw new RuntimeException("ip解析地址异常!");
  70. }
  71. return regionList;
  72. }
  73. }

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

闽ICP备14008679号