-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathget_ip.go
90 lines (73 loc) · 1.41 KB
/
get_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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package main
import (
"log"
"net"
"regexp"
"strings"
)
type lookupExternalIPUrl struct {
v4 string
v6 string
}
type externalIPAddress struct {
v4 string
v6 string
}
var lookupExternalIPUrls = []lookupExternalIPUrl{
{
v4: "https://v4.ifconfig.co/ip",
v6: "https://v6.ifconfig.co/ip",
},
{
v4: "http://myexternalip.com/raw",
},
}
func isIPValid(addr string) bool {
if addr != "" {
ip := net.ParseIP(addr)
return !(ip == nil)
}
return false
}
func getIP(url string, regexp *regexp.Regexp) (string, error) {
var addr string
body, err := getURL(url, nil)
if err != nil {
return "", err
}
if regexp != nil {
result := regexp.FindAllStringSubmatch(string(body), -1)
if len(result) > 0 && len(result[0]) > 0 {
addr = result[0][1]
}
} else {
addr = strings.Trim(string(body), " \r\n")
}
if !isIPValid(addr) {
addr = ""
}
return addr, nil
}
func getExternalIP(conf *config) *externalIPAddress {
var IPv4, IPv6 string
var err error
for _, lookup := range lookupExternalIPUrls {
IPv4, err = getIP(lookup.v4, nil)
if err != nil {
log.Printf("%s", err.Error())
}
if conf.SetIPv6 {
IPv6, err = getIP(lookup.v6, nil)
if err != nil {
log.Printf("%s", err.Error())
}
}
if len(IPv4) > 0 || len(IPv6) > 0 {
break
}
}
if len(IPv4) == 0 && len(IPv6) == 0 {
log.Fatal("couldn't determine external IP address")
}
return &externalIPAddress{v4: IPv4, v6: IPv6}
}