This repository has been archived by the owner on Jan 11, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
81 lines (73 loc) · 1.44 KB
/
utils.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
package main
import (
"errors"
"io/ioutil"
"log"
"net"
"net/http"
"strings"
)
//
// GetOwnIP retuns the machines external net.IP address
//
func GetOwnIP(dialAddress string) (net.IP, error) {
addrs, err := net.InterfaceAddrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
ip := net.ParseIP(addr.String())
if ip == nil {
continue
}
if IsPublicIP(ip) {
return ip, nil
}
}
return QueryIP(dialAddress)
}
//
// QueryIP fetches external IP from IPDetectionSite using a GET request and parsing the content
//
func QueryIP(dialAddress string) (net.IP, error) {
resp, err := http.Get(dialAddress)
if err != nil {
return nil, err
}
defer func() {
derr := resp.Body.Close()
if derr != nil {
log.Println("ERORR:", derr)
}
}()
ipBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
ip := net.ParseIP(strings.TrimSpace(string(ipBytes)))
if ip != nil {
return ip, nil
}
return nil, errors.New("unable to detect external IP address")
}
//
// IsPublicIP returns true for a public IP beeing passed
//
func IsPublicIP(IP net.IP) bool {
if IP.IsLoopback() || IP.IsLinkLocalMulticast() || IP.IsLinkLocalUnicast() {
return false
}
if ip4 := IP.To4(); ip4 != nil {
switch true {
case ip4[0] == 10:
return false
case ip4[0] == 172 && ip4[1] >= 16 && ip4[1] <= 31:
return false
case ip4[0] == 192 && ip4[1] == 168:
return false
default:
return true
}
}
return false
}