github.com/MetalBlockchain/metalgo@v1.11.9/utils/ips/lookup.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package ips 5 6 import ( 7 "errors" 8 "net" 9 "net/netip" 10 ) 11 12 var errNoIPsFound = errors.New("no IPs found") 13 14 // Lookup attempts to resolve a hostname to a single IP. If multiple IPs are 15 // found, then lookup will attempt to return an IPv4 address, otherwise it will 16 // pick any of the IPs. 17 // 18 // Note: IPv4 is preferred because `net.Listen` prefers IPv4. 19 func Lookup(hostname string) (netip.Addr, error) { 20 ips, err := net.LookupIP(hostname) 21 if err != nil { 22 return netip.Addr{}, err 23 } 24 if len(ips) == 0 { 25 return netip.Addr{}, errNoIPsFound 26 } 27 28 for _, ip := range ips { 29 ipv4 := ip.To4() 30 if ipv4 != nil { 31 addr, _ := AddrFromSlice(ipv4) 32 return addr, nil 33 } 34 } 35 addr, _ := AddrFromSlice(ips[0]) 36 return addr, nil 37 }