forked from cloudfoundry/bosh-bootloader
/
ip.go
60 lines (48 loc) · 1012 Bytes
/
ip.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
package bosh
import (
"fmt"
"strconv"
"strings"
)
type IP struct {
ip int
}
func ParseIP(ip string) (IP, error) {
const IP_PARTS = 4
const MAX_IP_PART = 256
ipParts := strings.Split(ip, ".")
if len(ipParts) != IP_PARTS {
return IP{}, fmt.Errorf(`'%s' is not a valid ip address`, ip)
}
ipValue := 0
for _, ipPart := range ipParts {
ipPartInt, err := strconv.Atoi(ipPart)
if err != nil {
return IP{}, err
}
if ipPartInt < 0 || ipPartInt >= MAX_IP_PART {
return IP{}, fmt.Errorf("invalid ip, %s has values out of range", ip)
}
ipValue = ipValue*MAX_IP_PART + ipPartInt
}
return IP{
ip: ipValue,
}, nil
}
func (i IP) Add(offset int) IP {
return IP{
ip: i.ip + offset,
}
}
func (i IP) Subtract(offset int) IP {
return IP{
ip: i.ip - offset,
}
}
func (i IP) String() string {
first := i.ip & 0xff000000 >> 24
second := i.ip & 0xff0000 >> 16
third := i.ip & 0xff00 >> 8
fourth := i.ip & 0xff
return fmt.Sprintf("%v.%v.%v.%v", first, second, third, fourth)
}