github.com/MetalBlockchain/metalgo@v1.11.9/utils/dynamicip/ifconfig_resolver.go (about) 1 // Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved. 2 // See the file LICENSE for licensing terms. 3 4 package dynamicip 5 6 import ( 7 "context" 8 "fmt" 9 "io" 10 "net/http" 11 "net/netip" 12 "strings" 13 14 "github.com/MetalBlockchain/metalgo/utils/ips" 15 ) 16 17 var _ Resolver = (*ifConfigResolver)(nil) 18 19 // ifConfigResolver resolves our public IP using ifconfig's format. 20 type ifConfigResolver struct { 21 url string 22 } 23 24 func (r *ifConfigResolver) Resolve(ctx context.Context) (netip.Addr, error) { 25 req, err := http.NewRequestWithContext(ctx, http.MethodGet, r.url, nil) 26 if err != nil { 27 return netip.Addr{}, err 28 } 29 30 resp, err := http.DefaultClient.Do(req) 31 if err != nil { 32 return netip.Addr{}, err 33 } 34 defer resp.Body.Close() 35 36 ipBytes, err := io.ReadAll(resp.Body) 37 if err != nil { 38 // Drop any error to report the original error 39 return netip.Addr{}, fmt.Errorf("failed to read response from %q: %w", r.url, err) 40 } 41 42 ipStr := strings.TrimSpace(string(ipBytes)) 43 return ips.ParseAddr(ipStr) 44 }