/
ip_helper.go
49 lines (38 loc) · 1.23 KB
/
ip_helper.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
package system
import (
"errors"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
"strconv"
"strings"
)
func CalculateNetworkAndBroadcast(ipAddress, netmask string) (network, broadcast string, err error) {
ipComponents := strings.Split(ipAddress, ".")
maskComponents := strings.Split(netmask, ".")
if len(ipComponents) != 4 || len(maskComponents) != 4 {
err = errors.New("Invalid ip or netmask")
return
}
networkComponents := []string{}
broadcastComponents := []string{}
for i := 0; i < 4; i++ {
var ipComponent int
var maskComponent int
ipComponent, err = strconv.Atoi(ipComponents[i])
if err != nil {
err = bosherr.WrapError(err, "Parsing number from ip address")
return
}
maskComponent, err = strconv.Atoi(maskComponents[i])
if err != nil {
err = bosherr.WrapError(err, "Parsing number from netmask")
return
}
networkComponent := strconv.Itoa(ipComponent & maskComponent)
broadcastComponent := strconv.Itoa((ipComponent | (^maskComponent)) & 255)
networkComponents = append(networkComponents, networkComponent)
broadcastComponents = append(broadcastComponents, broadcastComponent)
}
network = strings.Join(networkComponents, ".")
broadcast = strings.Join(broadcastComponents, ".")
return
}