github.com/v2fly/v2ray-core/v5@v5.16.2-0.20240507031116-8191faa6e095/app/dns/nameserver_local.go (about)

     1  //go:build !confonly
     2  // +build !confonly
     3  
     4  package dns
     5  
     6  import (
     7  	"context"
     8  
     9  	"github.com/v2fly/v2ray-core/v5/common/net"
    10  	"github.com/v2fly/v2ray-core/v5/features/dns"
    11  	"github.com/v2fly/v2ray-core/v5/features/dns/localdns"
    12  )
    13  
    14  // LocalNameServer is an wrapper over local DNS feature.
    15  type LocalNameServer struct {
    16  	client *localdns.Client
    17  }
    18  
    19  // QueryIP implements Server.
    20  func (s *LocalNameServer) QueryIP(_ context.Context, domain string, _ net.IP, option dns.IPOption, _ bool) ([]net.IP, error) {
    21  	var ips []net.IP
    22  	var err error
    23  
    24  	switch {
    25  	case option.IPv4Enable && option.IPv6Enable:
    26  		ips, err = s.client.LookupIP(domain)
    27  	case option.IPv4Enable:
    28  		ips, err = s.client.LookupIPv4(domain)
    29  	case option.IPv6Enable:
    30  		ips, err = s.client.LookupIPv6(domain)
    31  	}
    32  
    33  	if len(ips) > 0 {
    34  		newError("Localhost got answer: ", domain, " -> ", ips).AtInfo().WriteToLog()
    35  	}
    36  
    37  	return ips, err
    38  }
    39  
    40  // Name implements Server.
    41  func (s *LocalNameServer) Name() string {
    42  	return "localhost"
    43  }
    44  
    45  // NewLocalNameServer creates localdns server object for directly lookup in system DNS.
    46  func NewLocalNameServer() *LocalNameServer {
    47  	newError("DNS: created localhost client").AtInfo().WriteToLog()
    48  	return &LocalNameServer{
    49  		client: localdns.New(),
    50  	}
    51  }
    52  
    53  // NewLocalDNSClient creates localdns client object for directly lookup in system DNS.
    54  func NewLocalDNSClient() *Client {
    55  	return &Client{server: NewLocalNameServer()}
    56  }