client.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. package localdns
  2. import (
  3. "github.com/v2fly/v2ray-core/v4/common/net"
  4. "github.com/v2fly/v2ray-core/v4/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) ([]net.IP, error) {
  18. ips, err := net.LookupIP(host)
  19. if err != nil {
  20. return nil, err
  21. }
  22. parsedIPs := make([]net.IP, 0, len(ips))
  23. for _, ip := range ips {
  24. parsed := net.IPAddress(ip)
  25. if parsed != nil {
  26. parsedIPs = append(parsedIPs, parsed.IP())
  27. }
  28. }
  29. if len(parsedIPs) == 0 {
  30. return nil, dns.ErrEmptyResponse
  31. }
  32. return parsedIPs, nil
  33. }
  34. // LookupIPv4 implements IPv4Lookup.
  35. func (c *Client) LookupIPv4(host string) ([]net.IP, error) {
  36. ips, err := c.LookupIP(host)
  37. if err != nil {
  38. return nil, err
  39. }
  40. ipv4 := make([]net.IP, 0, len(ips))
  41. for _, ip := range ips {
  42. if len(ip) == net.IPv4len {
  43. ipv4 = append(ipv4, ip)
  44. }
  45. }
  46. if len(ipv4) == 0 {
  47. return nil, dns.ErrEmptyResponse
  48. }
  49. return ipv4, nil
  50. }
  51. // LookupIPv6 implements IPv6Lookup.
  52. func (c *Client) LookupIPv6(host string) ([]net.IP, error) {
  53. ips, err := c.LookupIP(host)
  54. if err != nil {
  55. return nil, err
  56. }
  57. ipv6 := make([]net.IP, 0, len(ips))
  58. for _, ip := range ips {
  59. if len(ip) == net.IPv6len {
  60. ipv6 = append(ipv6, ip)
  61. }
  62. }
  63. if len(ipv6) == 0 {
  64. return nil, dns.ErrEmptyResponse
  65. }
  66. return ipv6, nil
  67. }
  68. // New create a new dns.Client that queries localhost for DNS.
  69. func New() *Client {
  70. return &Client{}
  71. }