github.com/telepresenceio/telepresence/v2@v2.20.0-pro.6.0.20240517030216-236ea954e789/pkg/dnsproxy/lookup_darwin.go (about)

     1  package dnsproxy
     2  
     3  import (
     4  	"bufio"
     5  	"bytes"
     6  	"context"
     7  	"strings"
     8  	"time"
     9  
    10  	"github.com/telepresenceio/telepresence/v2/pkg/iputil"
    11  	"github.com/telepresenceio/telepresence/v2/pkg/proc"
    12  )
    13  
    14  func externalLookup(ctx context.Context, host string, timeout time.Duration) iputil.IPs {
    15  	ctx, cancel := context.WithTimeout(ctx, timeout)
    16  	defer cancel()
    17  	cmd := proc.CommandContext(ctx, "dscacheutil", "-q", "host", "-a", "name", host)
    18  	cmd.DisableLogging = true
    19  	out, err := cmd.Output()
    20  	if err != nil {
    21  		return nil
    22  	}
    23  
    24  	// Look for the adjacent lines
    25  	//   Name: <host>
    26  	//   Address: <ip>
    27  	sc := bufio.NewScanner(bytes.NewReader(out))
    28  	var ips iputil.IPs
    29  	for sc.Scan() {
    30  		s := sc.Text()
    31  		if a := strings.TrimPrefix(s, "name: "); a != s && strings.HasPrefix(a, host) && sc.Scan() {
    32  			s = sc.Text()
    33  			if a := strings.TrimPrefix(s, "ip_address: "); a != s {
    34  				if ip := iputil.Parse(a); ip != nil {
    35  					ips = append(ips, ip)
    36  				}
    37  			} else if a := strings.TrimPrefix(s, "ipv6_address: "); a != s {
    38  				if ip := iputil.Parse(a); ip != nil {
    39  					ips = append(ips, ip)
    40  				}
    41  			}
    42  		}
    43  	}
    44  	return ips
    45  }