IpTool.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using IP2Region.Net.XDB;
  2. using System;
  3. using System.IO;
  4. using ZR.Infrastructure.IPTools.Model;
  5. namespace ZR.Infrastructure.IPTools
  6. {
  7. public class IpTool
  8. {
  9. private static readonly string DbPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ip2region.xdb");
  10. private static readonly Searcher Searcher;
  11. static IpTool()
  12. {
  13. if (!File.Exists(DbPath))
  14. {
  15. throw new Exception($"IP initialize failed. Can not find database file from {DbPath}. Please download the file to your application root directory, then set it can be copied to the output directory. Url: https://gitee.com/lionsoul/ip2region/blob/master/data/ip2region.xdb");
  16. }
  17. Searcher = new Searcher(CachePolicy.File, DbPath);
  18. }
  19. public static string GetRegion(string ip)
  20. {
  21. if (string.IsNullOrEmpty(ip))
  22. {
  23. throw new ArgumentException("IP为空", nameof(ip));
  24. }
  25. try
  26. {
  27. var region = Searcher.Search(ip);
  28. return region;
  29. }
  30. catch (Exception ex)
  31. {
  32. Console.WriteLine(ex.Message);
  33. throw new Exception($"搜索IP异常IP={ip}", ex);
  34. }
  35. }
  36. public static IpInfo Search(string ip)
  37. {
  38. try
  39. {
  40. var region = GetRegion(ip);
  41. var array = region.Split("|");
  42. var info = new IpInfo()
  43. {
  44. Country = array[0],
  45. Province = array[2],
  46. City = array[3],
  47. NetworkOperator = array[4],
  48. IpAddress = ip
  49. };
  50. return info;
  51. }
  52. catch (Exception e)
  53. {
  54. throw new Exception("Error converting ip address information to ipinfo object", e);
  55. }
  56. }
  57. }
  58. }