-
Notifications
You must be signed in to change notification settings - Fork 0
/
netaddress.go
71 lines (54 loc) · 1.28 KB
/
netaddress.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
package main
import (
"fmt"
"net"
)
type netAddress struct {
net.IPNet
}
func (netaddr netAddress) String() string {
return netaddr.IPNet.String()
}
func (netaddr netAddress) MarshalText() ([]byte, error) {
return []byte(netaddr.String()), nil
}
func (netaddr *netAddress) UnmarshalText(text []byte) error {
raw := string(text)
// Parse CIDR notation IP address and prefix length, like "192.0.2.0/24" or
// "2001:db8::/32"
ip, ipnet, err := net.ParseCIDR(raw)
if err == nil {
netaddr.IP = ipnet.IP
netaddr.Mask = ipnet.Mask
} else {
// Attempt to parse without prefix length
ip = net.ParseIP(raw)
if ip == nil {
return fmt.Errorf("Parsing IP address %q failed", raw)
}
netaddr.IP = ip
if ip = netaddr.IP.To4(); ip == nil {
ip = netaddr.IP.To16()
}
if ip == nil {
return fmt.Errorf("Unknown IP address type")
}
netaddr.IP = ip
netaddr.Mask = net.CIDRMask(8*len(ip), 8*len(ip))
}
return nil
}
func parseNetAddress(text string) (netAddress, error) {
result := netAddress{}
if err := result.UnmarshalText([]byte(text)); err != nil {
return result, err
}
return result, nil
}
func mustParseNetAddress(text string) netAddress {
result := netAddress{}
if err := result.UnmarshalText([]byte(text)); err != nil {
panic(err)
}
return result
}