-
Notifications
You must be signed in to change notification settings - Fork 8
/
netaddr.go
102 lines (88 loc) · 2.05 KB
/
netaddr.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
/*
netaddr is a Go library for performing calculations on IPv4 and IPv6 subnets. There is also limited support for EUI addresses.
*/
package netaddr
import (
"strconv"
"strings"
)
const (
// 32 bits worth of '1'
F32 uint32 = 0xffffffff
// 64 bits worth of '1'
F64 uint64 = 0xffffffffffffffff
)
type IP interface{
String() string
Version() uint
}
type IPNet interface{
String() string
Version() uint
}
// IPv4PrefixLen returns the prefix length needed to hold the
// number of IP addresses specified by "size".
func IPv4PrefixLen(size uint) uint {
var prefix uint
for prefix = 32; prefix >= 0; prefix -= 1 {
hostbits := 32 - prefix
var max uint = 1 << hostbits
if size <= max {
break
}
}
return prefix
}
// ParseIP parses a string into an IP
func ParseIP(ip string) (IP,error){
if strings.Contains(ip, ":"){
return ParseIPv6(ip)
}
return ParseIPv4(ip)
}
// ParseIPNet parses a string into an IPNet
func ParseIPNet(net string) (IPNet,error){
if strings.Contains(net, ":"){
return ParseIPv6Net(net)
}
return ParseIPv4Net(net)
}
// NON EXPORTED
// cleanupEUI removes delimiter characters from eui address string
func cleanupEUI(addr string) string {
addr = strings.TrimSpace(addr)
addr = strings.Replace(addr, ":", "", -1)
addr = strings.Replace(addr, "-", "", -1)
addr = strings.Replace(addr, ".", "", -1)
return addr
}
// u8SlicetoU32 converts a slice of 4 strings representing uint8 numbers (base 10) to a uint32.
func u8SlicetoU32(group []string) (uint32, error) {
var g uint64 = 4
var u32 uint32
for _, e := range group {
g -= 1
u8, err := strconv.ParseUint(e, 10, 8)
if err != nil {
return 0, err
}
u8 = u8 << (8 * g)
u32 = u32 | uint32(u8)
}
return u32, nil
}
// u16SlicetoU64 converts a slice of 4 strings representing uint16 numbers (in hex) to a uint64.
func u16SlicetoU64(group []string) (uint64, error) {
var g uint64 = 4
var u64 uint64
for _, e := range group {
g -= 1
u16, err := strconv.ParseUint(e, 16, 16)
if err != nil {
return 0, err
}
u16 = u16 << (16 * g)
u64 = u64 | u16
}
return u64, nil
}