httpdns.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. --[[
  2. @module httpdns
  3. @summary 使用Http进行域名解析
  4. @version 1.0
  5. @date 2023.07.13
  6. @author wendal
  7. @usage
  8. -- 通过阿里DNS获取结果
  9. local ip = httpdns.ali("air32.cn")
  10. log.info("httpdns", "air32.cn", ip)
  11. -- 通过腾讯DNS获取结果
  12. local ip = httpdns.tx("air32.cn")
  13. log.info("httpdns", "air32.cn", ip)
  14. ]]
  15. local httpdns = {}
  16. --[[
  17. 通过阿里DNS获取结果
  18. @api httpdns.ali(domain_name, opts)
  19. @string 域名
  20. @table opts 可选参数, 与http.request的opts参数一致
  21. @return string ip地址
  22. @usage
  23. local ip = httpdns.ali("air32.cn")
  24. log.info("httpdns", "air32.cn", ip)
  25. -- 指定网络适配器
  26. local ip = httpdns.ali("air32.cn", {adapter=socket.LWIP_STA, timeout=3000})
  27. log.info("httpdns", "air32.cn", ip)
  28. ]]
  29. function httpdns.ali(n, opts)
  30. if n == nil then return end
  31. local code, _, body = http.request("GET", "http://223.5.5.5/resolve?short=1&name=" .. tostring(n), nil, nil, opts).wait()
  32. if code == 200 and body and #body > 2 then
  33. local jdata = json.decode(body)
  34. if jdata and #jdata > 0 then
  35. return jdata[1]
  36. end
  37. end
  38. end
  39. --[[
  40. 通过腾讯DNS获取结果
  41. @api httpdns.tx(domain_name, opts)
  42. @string 域名
  43. @table opts 可选参数, 与http.request的opts参数一致
  44. @return string ip地址
  45. @usage
  46. local ip = httpdns.tx("air32.cn")
  47. log.info("httpdns", "air32.cn", ip)
  48. -- 指定网络适配器
  49. local ip = httpdns.tx("air32.cn", {adapter=socket.LWIP_STA, timeout=3000})
  50. log.info("httpdns", "air32.cn", ip)
  51. ]]
  52. function httpdns.tx(n, opts)
  53. if n == nil then return end
  54. local code, _, body = http.request("GET", "http://119.29.29.29/d?dn=" .. tostring(n), nil, nil, opts).wait()
  55. if code == 200 and body and #body > 2 then
  56. local tmp = body:split(",")
  57. if tmp then return tmp[1] end
  58. end
  59. end
  60. return httpdns