-
Notifications
You must be signed in to change notification settings - Fork 0
/
ip.go
61 lines (56 loc) · 1.13 KB
/
ip.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package hopconn
import (
"fmt"
"io"
"net"
"net/http"
"os"
"time"
)
type IPProvider func() (string, error)
func DefaultPublicIP() (string, error) {
c := http.Client{
Transport: &http.Transport{
DisableKeepAlives: true,
},
Timeout: 5 * time.Second,
}
return GlobalIP(c)
}
func GlobalIP(client http.Client) (string, error) {
url := "https://api.ipify.org?format=text"
req, err := http.NewRequest(http.MethodGet, url, nil)
if err != nil {
return "", err
}
resp, err := client.Do(req)
if err != nil {
if os.IsTimeout(err) {
return "timeout", nil
}
return "", err
}
defer func() {
_ = resp.Body.Close()
}()
ip, err := io.ReadAll(resp.Body)
if err != nil {
return "", err
}
return string(ip), nil
}
func LocalIP() (string, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return "", err
}
for _, address := range addrs {
// check the address type and if it is not a loopback the display it
if ip, ok := address.(*net.IPNet); ok && !ip.IP.IsLoopback() {
if ip.IP.To4() != nil {
return ip.IP.String(), nil
}
}
}
return "", fmt.Errorf("could not figure out the IP of your machine")
}