PublicIPAddressTool.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. using Azylee.Core.DataUtils.StringUtils;
  2. using Azylee.Jsons;
  3. using Azylee.YeahWeb.HttpUtils;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. namespace Azylee.YeahWeb.ExtWebAPI.IPAddressAPI
  9. {
  10. /// <summary>
  11. /// 公网IP地址API
  12. /// </summary>
  13. public class PublicIPAddressTool
  14. {
  15. const string URL = "http://pv.sohu.com/cityjson?ie=utf-8";
  16. /// <summary>
  17. /// 获取公网IP地址API
  18. /// </summary>
  19. /// <returns></returns>
  20. public static PublicIPAddressModel GetPublicIP()
  21. {
  22. string rs = HttpTool.Get(URL);
  23. if (Str.Ok(rs))
  24. {
  25. int flagbeg = rs.IndexOf("{");
  26. int flagend = rs.LastIndexOf("}");
  27. if (flagbeg < flagend)
  28. {
  29. rs = rs.Substring(flagbeg, flagend - flagbeg + 1);
  30. Dictionary<string, string> model = Json.String2Object<Dictionary<string, string>>(rs);
  31. if (model != null)
  32. {
  33. model.TryGetValue("cip", out string cip);
  34. model.TryGetValue("cid", out string cid);
  35. model.TryGetValue("cname", out string cname);
  36. PublicIPAddressModel result = new PublicIPAddressModel(cip, cid, cname);
  37. return result;
  38. }
  39. }
  40. }
  41. return null;
  42. }
  43. }
  44. }