Files
gluetun/internal/publicip/publicip.go

73 lines
1.5 KiB
Go
Raw Normal View History

2021-02-06 16:26:23 +00:00
// Package publicip defines interfaces to get your public IP address.
2020-06-05 19:32:12 -04:00
package publicip
import (
"context"
2021-05-30 16:14:08 +00:00
"errors"
2020-06-05 19:32:12 -04:00
"fmt"
"io"
2020-06-05 19:32:12 -04:00
"math/rand"
"net"
"net/http"
"strings"
)
type IPGetter interface {
Get(ctx context.Context) (ip net.IP, err error)
2020-06-05 19:32:12 -04:00
}
type ipGetter struct {
client *http.Client
2020-06-05 19:32:12 -04:00
randIntn func(n int) int
}
func NewIPGetter(client *http.Client) IPGetter {
2020-06-05 19:32:12 -04:00
return &ipGetter{
client: client,
randIntn: rand.Intn,
}
}
2021-05-30 16:14:08 +00:00
var ErrParseIP = errors.New("cannot parse IP address")
func (i *ipGetter) Get(ctx context.Context) (ip net.IP, err error) {
2020-06-05 19:32:12 -04:00
urls := []string{
"https://ifconfig.me/ip",
2020-06-05 19:32:12 -04:00
"http://ip1.dynupdate.no-ip.com:8245",
"http://ip1.dynupdate.no-ip.com",
"https://api.ipify.org",
"https://diagnostic.opendns.com/myip",
"https://domains.google.com/checkip",
"https://ifconfig.io/ip",
"https://ipinfo.io/ip",
}
url := urls[i.randIntn(len(urls))]
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, err
}
response, err := i.client.Do(req)
2020-06-05 19:32:12 -04:00
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w from %s: %s", ErrBadStatusCode, url, response.Status)
}
content, err := io.ReadAll(response.Body)
if err != nil {
return nil, fmt.Errorf("%w: %s", ErrCannotReadBody, err)
}
2020-06-05 19:32:12 -04:00
s := strings.ReplaceAll(string(content), "\n", "")
ip = net.ParseIP(s)
if ip == nil {
2021-05-30 16:14:08 +00:00
return nil, fmt.Errorf("%w: %s", ErrParseIP, s)
2020-06-05 19:32:12 -04:00
}
return ip, nil
}