This repository has been archived by the owner on Sep 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 37
/
addresses.go
99 lines (79 loc) · 1.64 KB
/
addresses.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
91
92
93
94
95
96
97
98
99
package main
import (
"errors"
"net"
)
var privateBlocks []*net.IPNet
func setupIPBlocks() {
privateBlockStrs := []string{
"10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16",
}
privateBlocks = make([]*net.IPNet, len(privateBlockStrs))
for i, blockStr := range privateBlockStrs {
_, block, _ := net.ParseCIDR(blockStr)
privateBlocks[i] = block
}
}
func isPrivateIP(ip_str string) bool {
ip := net.ParseIP(ip_str)
for _, priv := range privateBlocks {
if priv.Contains(ip) {
return true
}
}
return false
}
func findPrivateAddresses() ([]*net.IP, error) {
if len(privateBlocks) < 1 {
setupIPBlocks()
}
addresses, err := net.InterfaceAddrs()
if err != nil {
return nil, errors.New(
"Failed to get interface addresses! Err: " + err.Error(),
)
}
result := make([]*net.IP, 0, len(addresses))
// Find private IPv4 address
for _, rawAddr := range addresses {
var ip net.IP
switch addr := rawAddr.(type) {
case *net.IPAddr:
ip = addr.IP
case *net.IPNet:
ip = addr.IP
default:
continue
}
if ip.To4() == nil {
continue
}
if isPrivateIP(ip.String()) {
result = append(result, &ip)
}
}
err = nil
if len(result) < 1 {
err = errors.New("No addresses found!")
result = nil
}
return result, err
}
func getPublishedIP(excluded []string, advertise string) (string, error) {
if advertise != "" {
return advertise, nil
}
addresses, _ := findPrivateAddresses()
OUTER:
for _, address := range addresses {
for _, excludeIP := range excluded {
if address.String() == excludeIP {
continue OUTER
}
}
return address.String(), nil
}
return "", errors.New("Can't find address!")
}