-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
address.go
102 lines (84 loc) · 2.33 KB
/
address.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
package util
import (
"encoding/binary"
"net"
)
// Address is an IP abstraction that is family (v4/v6) agnostic
type Address interface {
Bytes() []byte
String() string
IsLoopback() bool
}
// AddressFromNetIP returns an Address from a provided net.IP
func AddressFromNetIP(ip net.IP) Address {
if v4 := ip.To4(); v4 != nil {
var a v4Address
copy(a[:], v4)
return a
}
var a v6Address
copy(a[:], ip)
return a
}
// AddressFromString creates an Address using the string representation of an v4 IP
func AddressFromString(ip string) Address {
return AddressFromNetIP(net.ParseIP(ip))
}
// NetIPFromAddress returns a net.IP from an Address
func NetIPFromAddress(addr Address) net.IP {
return net.IP(addr.Bytes())
}
type v4Address [4]byte
// V4Address creates an Address using the uint32 representation of an v4 IP
func V4Address(ip uint32) Address {
var a v4Address
a[0] = byte(ip)
a[1] = byte(ip >> 8)
a[2] = byte(ip >> 16)
a[3] = byte(ip >> 24)
return a
}
// V4AddressFromBytes creates an Address using the byte representation of an v4 IP
func V4AddressFromBytes(buf []byte) Address {
var a v4Address
copy(a[:], buf)
return a
}
// Bytes returns a byte array of the underlying array
func (a v4Address) Bytes() []byte {
return a[:]
}
// String returns the human readable string representation of an IP
func (a v4Address) String() string {
return net.IPv4(a[0], a[1], a[2], a[3]).String()
}
// IsLoopback returns true if this address is the loopback address
func (a v4Address) IsLoopback() bool {
return net.IP(a[:]).IsLoopback()
}
type v6Address [16]byte
// V6Address creates an Address using the uint128 representation of an v6 IP
func V6Address(low, high uint64) Address {
var a v6Address
binary.LittleEndian.PutUint64(a[:8], high)
binary.LittleEndian.PutUint64(a[8:], low)
return a
}
// V6AddressFromBytes creates an Address using the byte representation of an v6 IP
func V6AddressFromBytes(buf []byte) Address {
var a v6Address
copy(a[:], buf)
return a
}
// Bytes returns a byte array of the underlying array
func (a v6Address) Bytes() []byte {
return a[:]
}
// String returns the human readable string representation of an IP
func (a v6Address) String() string {
return net.IP(a[:]).String()
}
// IsLoopback returns true if this address is the loopback address
func (a v6Address) IsLoopback() bool {
return net.IP(a[:]).IsLoopback()
}