client.go 1.5 KB

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