-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipaddr.go
416 lines (375 loc) · 10.4 KB
/
ipaddr.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
// Copyright 2018 xgfone
//
// 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 netaddr
import (
"encoding/binary"
"fmt"
"math/big"
"net"
"strings"
)
// IPAddress represents a IPv4/IPv6 address.
type IPAddress struct {
ip net.IP
version int
}
// NewIPAddress returns a new IPAddress.
//
// The argument, ip, is a IPv4 or IPv6 address, which maybe a string, []byte,
// [4]byte, [16]byte, net.IP, *big.Int, int, int64, uint, uint32 or uint64.
//
// For *big.Int, the version is necessary, which reprensents the verion
// of the IP address, that's, 4 or 6.
//
// For int, int64, uint, uint32 and uint64, the version is 4 by default.
//
// For []byte, the version is necessary if the length of bytes is not 4 or 16.
//
// For string, it maybe either a ipv4/ipv6 address or a integer string.
// If it's a integer string, it represents the integer value of the ipv4/ipv6,
// and must appoint the version explicitly.
func NewIPAddress(ip interface{}, version ...int) (IPAddress, error) {
var _ip net.IP
var _version int
if len(version) > 0 {
_version = version[0]
if _version != 4 && _version != 6 {
return IPAddress{}, fmt.Errorf("version must be 4 or 6")
}
}
switch v := ip.(type) {
case int:
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, uint32(v))
_ip = net.IP(buf)
if _version == 0 {
_version = 4
}
case int64:
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, uint32(v))
_ip = net.IP(buf)
if _version == 0 {
_version = 4
}
case uint:
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, uint32(v))
_ip = net.IP(buf)
if _version == 0 {
_version = 4
}
case uint32:
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, uint32(v))
_ip = net.IP(buf)
if _version == 0 {
_version = 4
}
case uint64:
buf := make([]byte, 4)
binary.BigEndian.PutUint32(buf, uint32(v))
_ip = net.IP(buf)
if _version == 0 {
_version = 4
}
case string:
if _ip = net.ParseIP(v); _ip == nil {
bi, ok := new(big.Int).SetString(v, 10)
if !ok {
return IPAddress{}, fmt.Errorf("'%s' is not a valid ipv4/ipv6", ip)
}
if _version == 0 {
return IPAddress{}, fmt.Errorf("missing the argument 'version'")
}
return NewIPAddress(bi.Bytes(), _version)
}
if _version == 0 {
if strings.Contains(v, ":") {
_version = 6
} else {
_version = 4
}
}
case []byte:
switch _len := len(v); _len {
case net.IPv4len:
_version = 4
// _ip = net.IPv4(v[0], v[1], v[2], v[3])
_ip = net.IP(v)
case net.IPv6len:
_version = 6
_ip = net.IP(v)
default:
switch _version {
case 4:
if _len > net.IPv4len {
return IPAddress{}, fmt.Errorf("the bytes is too long")
} else if _len < net.IPv4len {
bs := [net.IPv4len]byte{}
copy(bs[net.IPv4len-_len:], v)
v = bs[:]
}
// _ip = net.IPv4(v[0], v[1], v[2], v[3])
_ip = net.IP(v)
case 6:
if _len > net.IPv6len {
return IPAddress{}, fmt.Errorf("the bytes is too long")
} else if _len < net.IPv6len {
bs := [net.IPv6len]byte{}
copy(bs[net.IPv6len-_len:], v)
v = bs[:]
}
_ip = net.IP(v)
default:
return IPAddress{}, fmt.Errorf("missing the argument 'version'")
}
}
case [4]byte:
_version = 4
// _ip = net.IPv4(v[0], v[1], v[2], v[3])
_ip = net.IP(v[:])
case [16]byte:
_version = 6
_ip = net.IP(v[:])
case net.IP:
if _version == 0 {
_version = len(v)
}
_ip = v
case *big.Int:
if _version == 0 {
return IPAddress{}, fmt.Errorf("missing the argument 'version'")
}
return NewIPAddress(v.Bytes(), _version)
default:
return IPAddress{}, fmt.Errorf("does not support the type '%T'", ip)
}
switch _version {
case 4:
return IPAddress{ip: _ip.To4(), version: 4}, nil
case 6:
return IPAddress{ip: _ip.To16(), version: 6}, nil
default:
return IPAddress{}, fmt.Errorf("the version '%d' is not 4 or 6", _version)
}
}
// MustNewIPAddress is the same as NewIPAddress, but panic if an error occurs.
func MustNewIPAddress(ip interface{}, version ...int) IPAddress {
addr, err := NewIPAddress(ip, version...)
if err != nil {
panic(err)
}
return addr
}
// IsValid reports whether the ip address is valid.
func (ip IPAddress) IsValid() bool {
v := ip.version
_len := len(ip.ip)
return (v == 4 && _len == 4) || (v == 6 && _len == 16) || false
}
// String returns a string representation of the ip address.
//
// It will return "" if the ip address is invalid.
func (ip IPAddress) String() string {
if ip.IsValid() {
return ip.ip.String()
}
return ""
}
// Bytes returns a []byte representation of the ip address.
func (ip IPAddress) Bytes() []byte {
return []byte(ip.ip)
}
// Version returns the version of ip.
func (ip IPAddress) Version() int {
return ip.version
}
// IP converts the ip to the type, net.IP.
func (ip IPAddress) IP() net.IP {
return ip.ip
}
// IPv4 returns a new IPv4 IPAddress.
func (ip IPAddress) IPv4() IPAddress {
if ip.version == 4 {
return ip
}
return IPAddress{ip: ip.ip.To4(), version: 4}
}
// IPv6 returns a new IPv6 IPAddress.
func (ip IPAddress) IPv6() IPAddress {
if ip.version == 6 {
return ip
}
return IPAddress{ip: ip.ip.To16(), version: 6}
}
// Value returns the integer string representation of the ipv4/ipv6 address.
func (ip IPAddress) Value() string {
bi := ip.BigInt()
if bi == nil {
return ""
}
return bi.String()
}
func (ip IPAddress) toBinary(sep string) string {
_len := len(ip.ip)
ss := make([]string, _len)
for i := 0; i < _len; i++ {
ss[i] = fmt.Sprintf("%08b", ip.ip[i])
}
return strings.Join(ss, sep)
}
// Binary returns the binary format of the IP address.
//
// For example, "10101010101010101010101010101010".
func (ip IPAddress) Binary() string {
return ip.toBinary("")
}
// Bits returns the binary format of the IP address separated by the dot.
//
// For example, "10101010.10101010.10101010.10101010".
func (ip IPAddress) Bits() string {
return ip.toBinary(".")
}
// Hex returns the hexadecimal format of the IP address.
//
// For example, "0a0b0c0d".
func (ip IPAddress) Hex() string {
_len := len(ip.ip)
ss := make([]string, 0, _len)
for i := 0; i < _len; i++ {
ss = append(ss, fmt.Sprintf("%02x", ip.ip[i]))
}
return strings.Join(ss, "")
}
// BigInt returns the big integer representation of the ipv4/ipv6 address.
func (ip IPAddress) BigInt() *big.Int {
switch ip.version {
case 4:
return new(big.Int).SetBytes(ip.IPv4().Bytes())
case 6:
return new(big.Int).SetBytes(ip.IPv6().Bytes())
}
return nil
}
// Network returns the network of the ip address.
func (ip IPAddress) Network() (net IPNetwork) {
var err error
switch ip.version {
case 4:
net, err = NewIPNetworkFromIPAddress(ip, ipv4MaxBit)
case 6:
net, err = NewIPNetworkFromIPAddress(ip, ipv6MaxBit)
default:
return IPNetwork{}
}
if err != nil {
panic(err)
}
return net
}
// Equal reports whether ip is equal to other.
func (ip IPAddress) Equal(other IPAddress) bool {
return ip.ip.Equal(other.ip)
}
// Compare returns an integer comparing two IPAddresses.
// The result will be 0 if ip==other, -1 if ip < other, and +1 if ip > other.
func (ip IPAddress) Compare(other IPAddress) int {
len1 := len(ip.ip)
len2 := len(other.ip)
if len1 != len2 {
panic(fmt.Errorf("the version is not consistent"))
}
for i := 0; i < len1; i++ {
if ip.ip[i] > other.ip[i] {
return 1
} else if ip.ip[i] < other.ip[i] {
return -1
}
}
return 0
}
// Less reports whether ip is less than other.
func (ip IPAddress) Less(other IPAddress) bool {
return ip.Compare(other) < 0
}
// IsIPv4 reports whether the ip address is ipv4.
func (ip IPAddress) IsIPv4() bool {
return ip.version == 4
}
// IsIPv6 reports whether the ip address is ipv6.
func (ip IPAddress) IsIPv6() bool {
return ip.version == 6
}
// IsUnspecified reports whether ip is an unspecified address, either
// the IPv4 address "0.0.0.0" or the IPv6 address "::".
func (ip IPAddress) IsUnspecified() bool {
return ip.ip.IsUnspecified()
}
// IsInterfaceLocalMulticast reports whether ip is
// an interface-local multicast address. that's, ff01::/16.
func (ip IPAddress) IsInterfaceLocalMulticast() bool {
return ip.ip.IsInterfaceLocalMulticast()
}
// IsLinkLocalMulticast reports whether ip is a link-local multicast address,
// that's, 224.0.0.0/24 or ff02::/16.
func (ip IPAddress) IsLinkLocalMulticast() bool {
return ip.ip.IsLinkLocalMulticast()
}
// IsLinkLocalUnicast reports whether ip is a link-local unicast address,
// that's, 169.254.0.0/16 or fe80::/10.
func (ip IPAddress) IsLinkLocalUnicast() bool {
return ip.ip.IsLinkLocalUnicast()
}
// IsGlobalUnicast reports whether ip is a global unicast
// address.
//
// The identification of global unicast addresses uses address type
// identification as defined in RFC 1122, RFC 4632 and RFC 4291 with
// the exception of IPv4 directed broadcast addresses.
// It returns true even if ip is in IPv4 private address space or
// local IPv6 unicast address space.
//
// They are not
// 0.0.0.0 255.255.255.255 127.0.0.0/8 169.254.0.0/16 224.0.0.0/4
// :: ::1 fe80::/10 ff00::/8
func (ip IPAddress) IsGlobalUnicast() bool {
return ip.ip.IsGlobalUnicast()
}
// IsUnicast reports whether the ip address is the unicast
func (ip IPAddress) IsUnicast() bool {
return !ip.IsMulticast()
}
// IsMulticast reports whether the ip address is the multicast,
// that's, 224.0.0.0/4 or ff00::/8.
func (ip IPAddress) IsMulticast() bool {
return ip.ip.IsMulticast()
}
// IsLoopback reports whether the ip address is the loopback,
// that's, 127.0.0.1/8 or ::1.
func (ip IPAddress) IsLoopback() bool {
return ip.ip.IsLoopback()
}
// Add returns a new IPAddress with its numerical value increased by num.
func (ip IPAddress) Add(num int64) IPAddress {
old := ip.BigInt()
old.Add(old, big.NewInt(num))
return MustNewIPAddress(old.Bytes(), ip.version)
}
// Sub returns a new IPAddress with its numerical value decreased by num.
func (ip IPAddress) Sub(num int64) IPAddress {
old := ip.BigInt()
old.Sub(old, big.NewInt(num))
return MustNewIPAddress(old.Bytes(), ip.version)
}