client.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package localdns
  2. import (
  3. "github.com/xtls/xray-core/common/net"
  4. "github.com/xtls/xray-core/features/dns"
  5. )
  6. // Client is an implementation of dns.Client, which queries localhost for DNS.
  7. type Client struct{}
  8. // Type implements common.HasType.
  9. func (*Client) Type() interface{} {
  10. return dns.ClientType()
  11. }
  12. // Start implements common.Runnable.
  13. func (*Client) Start() error { return nil }
  14. // Close implements common.Closable.
  15. func (*Client) Close() error { return nil }
  16. // LookupIP implements Client.
  17. func (*Client) LookupIP(host string, option dns.IPOption) ([]net.IP, uint32, error) {
  18. ips, err := net.LookupIP(host)
  19. if err != nil {
  20. return nil, 0, err
  21. }
  22. parsedIPs := make([]net.IP, 0, len(ips))
  23. ipv4 := make([]net.IP, 0, len(ips))
  24. ipv6 := make([]net.IP, 0, len(ips))
  25. for _, ip := range ips {
  26. parsed := net.IPAddress(ip)
  27. if parsed == nil {
  28. continue
  29. }
  30. parsedIP := parsed.IP()
  31. parsedIPs = append(parsedIPs, parsedIP)
  32. if len(parsedIP) == net.IPv4len {
  33. ipv4 = append(ipv4, parsedIP)
  34. } else {
  35. ipv6 = append(ipv6, parsedIP)
  36. }
  37. }
  38. switch {
  39. case option.IPv4Enable && option.IPv6Enable:
  40. if len(parsedIPs) > 0 {
  41. return parsedIPs, dns.DefaultTTL, nil
  42. }
  43. case option.IPv4Enable:
  44. if len(ipv4) > 0 {
  45. return ipv4, dns.DefaultTTL, nil
  46. }
  47. case option.IPv6Enable:
  48. if len(ipv6) > 0 {
  49. return ipv6, dns.DefaultTTL, nil
  50. }
  51. }
  52. return nil, 0, dns.ErrEmptyResponse
  53. }
  54. // New create a new dns.Client that queries localhost for DNS.
  55. func New() *Client {
  56. return &Client{}
  57. }