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 (
|
2020-10-18 02:24:34 +00:00
|
|
|
"context"
|
2021-05-30 16:14:08 +00:00
|
|
|
"errors"
|
2020-06-05 19:32:12 -04:00
|
|
|
"fmt"
|
2021-05-30 03:13:19 +00:00
|
|
|
"io"
|
2020-06-05 19:32:12 -04:00
|
|
|
"math/rand"
|
|
|
|
|
"net"
|
|
|
|
|
"net/http"
|
|
|
|
|
"strings"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type IPGetter interface {
|
2020-10-18 02:24:34 +00:00
|
|
|
Get(ctx context.Context) (ip net.IP, err error)
|
2020-06-05 19:32:12 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type ipGetter struct {
|
2020-12-29 02:55:34 +00:00
|
|
|
client *http.Client
|
2020-06-05 19:32:12 -04:00
|
|
|
randIntn func(n int) int
|
|
|
|
|
}
|
|
|
|
|
|
2020-12-29 02:55:34 +00:00
|
|
|
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")
|
|
|
|
|
|
2020-10-18 02:24:34 +00:00
|
|
|
func (i *ipGetter) Get(ctx context.Context) (ip net.IP, err error) {
|
2020-06-05 19:32:12 -04:00
|
|
|
urls := []string{
|
2020-07-08 22:47:48 +00:00
|
|
|
"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))]
|
2020-12-29 02:55:34 +00:00
|
|
|
|
|
|
|
|
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
|
|
|
|
|
}
|
2020-12-29 02:55:34 +00:00
|
|
|
defer response.Body.Close()
|
|
|
|
|
|
|
|
|
|
if response.StatusCode != http.StatusOK {
|
|
|
|
|
return nil, fmt.Errorf("%w from %s: %s", ErrBadStatusCode, url, response.Status)
|
|
|
|
|
}
|
|
|
|
|
|
2021-05-30 03:13:19 +00:00
|
|
|
content, err := io.ReadAll(response.Body)
|
2020-12-29 02:55:34 +00:00
|
|
|
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
|
|
|
|
|
}
|