-
Notifications
You must be signed in to change notification settings - Fork 262
/
ipv4.go
129 lines (112 loc) · 2.58 KB
/
ipv4.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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/*
* Copyright 2022 The Dragonfly Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ip
import (
"fmt"
"net"
"os"
)
var (
// IPv4 is external address.
IPv4 net.IP
// IPv4lookback is lookback address.
IPv4lookback = net.ParseIP("127.0.0.1")
)
func init() {
ip, err := externalIPv4()
if err != nil {
IPv4 = IPv4lookback
} else {
IPv4 = ip
}
}
// externalIPv4 returns the available IPv4.
func externalIPv4() (net.IP, error) {
ips, err := ipAddrs()
if err != nil {
return nil, err
}
var externalIPs []net.IP
for _, ip := range ips {
ip = ip.To4()
if ip == nil {
continue // not an ipv4 address
}
externalIPs = append(externalIPs, ip)
}
if len(externalIPs) == 0 {
return nil, fmt.Errorf("can not found external ipv4")
}
return externalIPs[0], nil
}
// ipAddrs returns all the valid IPs available.
// refer to https://github.com/dragonflyoss/Dragonfly2/pull/652
func ipAddrs() ([]net.IP, error) {
// use prefer ip possible
var prefers []net.IP
host, err := os.Hostname()
if err == nil {
ips, _ := net.LookupIP(host)
for _, ip := range ips {
if ip == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
continue
}
prefers = append(prefers, ip)
}
}
ifaces, err := net.Interfaces()
if err != nil {
return nil, err
}
var preferIPs []net.IP
var normalIPs []net.IP
for _, iface := range ifaces {
if iface.Flags&net.FlagUp == 0 {
continue // interface down
}
if iface.Flags&net.FlagLoopback != 0 {
continue // loopback interface
}
addrs, err := iface.Addrs()
if err != nil {
return nil, err
}
for _, addr := range addrs {
var ip net.IP
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
case *net.IPAddr:
ip = v.IP
}
if ip == nil || ip.IsLoopback() || ip.IsLinkLocalUnicast() {
continue
}
var isPrefer bool
for _, preferAddr := range prefers {
if preferAddr.Equal(ip) {
isPrefer = true
}
}
if isPrefer {
preferIPs = append(preferIPs, ip)
} else {
normalIPs = append(normalIPs, ip)
}
}
}
return append(preferIPs, normalIPs...), nil
}