httpdns.lua 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. if opts == nil then
  32. opts = {timeout=3000}
  33. elseif opts.timeout == nil then
  34. opts.timeout = 3000
  35. end
  36. local code, _, body = http.request("GET", "http://223.5.5.5/resolve?short=1&name=" .. tostring(n), nil, nil, opts).wait()
  37. if code == 200 and body and #body > 2 then
  38. local jdata = json.decode(body)
  39. if jdata and #jdata > 0 then
  40. return jdata[1]
  41. end
  42. end
  43. end
  44. --[[
  45. 通过腾讯DNS获取结果
  46. @api httpdns.tx(domain_name, opts)
  47. @string 域名
  48. @table opts 可选参数, 与http.request的opts参数一致
  49. @return string ip地址
  50. @usage
  51. local ip = httpdns.tx("air32.cn")
  52. log.info("httpdns", "air32.cn", ip)
  53. -- 指定网络适配器
  54. local ip = httpdns.tx("air32.cn", {adapter=socket.LWIP_STA, timeout=3000})
  55. log.info("httpdns", "air32.cn", ip)
  56. ]]
  57. function httpdns.tx(n, opts)
  58. if n == nil then return end
  59. if opts == nil then
  60. opts = {timeout=3000}
  61. elseif opts.timeout == nil then
  62. opts.timeout = 3000
  63. end
  64. local code, _, body = http.request("GET", "http://119.29.29.29/d?dn=" .. tostring(n), nil, nil, opts).wait()
  65. if code == 200 and body and #body > 2 then
  66. local tmp = body:split(",")
  67. if tmp then return tmp[1] end
  68. end
  69. end
  70. return httpdns