github.com/laof/lite-speed-test@v0.0.0-20230930011949-1f39b7037845/transport/resolver/resolver.go (about)

     1  package resolver
     2  
     3  import (
     4  	"errors"
     5  	"net"
     6  	"strings"
     7  )
     8  
     9  var (
    10  	ErrIPNotFound   = errors.New("couldn't find ip")
    11  	ErrIPVersion    = errors.New("ip version error")
    12  	ErrIPv6Disabled = errors.New("ipv6 disabled")
    13  )
    14  
    15  type Resolver interface {
    16  	ResolveIP(host string) (ip net.IP, err error)
    17  	ResolveIPv4(host string) (ip net.IP, err error)
    18  	ResolveIPv6(host string) (ip net.IP, err error)
    19  }
    20  
    21  var (
    22  	// DefaultResolver aim to resolve ip
    23  	DefaultResolver Resolver
    24  
    25  	// DisableIPv6 means don't resolve ipv6 host
    26  	// default value is true
    27  	DisableIPv6 = true
    28  )
    29  
    30  // ResolveIPv4 with a host, return ipv4
    31  func ResolveIPv4(host string) (net.IP, error) {
    32  
    33  	ip := net.ParseIP(host)
    34  	if ip != nil {
    35  		if !strings.Contains(host, ":") {
    36  			return ip, nil
    37  		}
    38  		return nil, ErrIPVersion
    39  	}
    40  
    41  	if DefaultResolver != nil {
    42  		return DefaultResolver.ResolveIPv4(host)
    43  	}
    44  
    45  	ipAddrs, err := net.LookupIP(host)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	for _, ip := range ipAddrs {
    51  		if ip4 := ip.To4(); ip4 != nil {
    52  			return ip4, nil
    53  		}
    54  	}
    55  
    56  	return nil, ErrIPNotFound
    57  }
    58  
    59  // ResolveIPv6 with a host, return ipv6
    60  func ResolveIPv6(host string) (net.IP, error) {
    61  
    62  	ip := net.ParseIP(host)
    63  	if ip != nil {
    64  		if strings.Contains(host, ":") {
    65  			return ip, nil
    66  		}
    67  		return nil, ErrIPVersion
    68  	}
    69  
    70  	if DefaultResolver != nil {
    71  		return DefaultResolver.ResolveIPv6(host)
    72  	}
    73  
    74  	ipAddrs, err := net.LookupIP(host)
    75  	if err != nil {
    76  		return nil, err
    77  	}
    78  
    79  	for _, ip := range ipAddrs {
    80  		if ip.To4() == nil {
    81  			return ip, nil
    82  		}
    83  	}
    84  
    85  	return nil, ErrIPNotFound
    86  }
    87  
    88  func ResolveIP(host string) (net.IP, error) {
    89  	ip := net.ParseIP(host)
    90  	if ip != nil {
    91  		return ip, nil
    92  	}
    93  
    94  	if DefaultResolver != nil {
    95  		return DefaultResolver.ResolveIP(host)
    96  	}
    97  
    98  	ipAddr, err := net.ResolveIPAddr("ip", host)
    99  	if err != nil {
   100  		return nil, err
   101  	}
   102  
   103  	return ipAddr.IP, nil
   104  }