-
Notifications
You must be signed in to change notification settings - Fork 660
/
ifconfig_resolver.go
47 lines (39 loc) · 1 KB
/
ifconfig_resolver.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
// Copyright (C) 2019-2023, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.
package dynamicip
import (
"context"
"fmt"
"io"
"net"
"net/http"
"strings"
)
var _ Resolver = (*ifConfigResolver)(nil)
// ifConfigResolver resolves our public IP using ifconfig's format.
type ifConfigResolver struct {
url string
}
func (r *ifConfigResolver) Resolve(ctx context.Context) (net.IP, error) {
req, err := http.NewRequestWithContext(ctx, "GET", r.url, nil)
if err != nil {
return nil, err
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
ipBytes, err := io.ReadAll(resp.Body)
if err != nil {
// Drop any error to report the original error
return nil, fmt.Errorf("failed to read response from %q: %w", r.url, err)
}
ipStr := string(ipBytes)
ipStr = strings.TrimSpace(ipStr)
ipResolved := net.ParseIP(ipStr)
if ipResolved == nil {
return nil, fmt.Errorf("couldn't parse IP from %q", ipStr)
}
return ipResolved, nil
}