go语言渐入佳境-网络[2]-ipmask

IPMask

ipmask存储掩码,掩码是指定ip地址中前多少位是网络地址的。
type IPMask []byte

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
/* Mask
*/

package main

import (
"fmt"
"net"
"os"
)

func main() {
if len(os.Args) != 2 {
fmt.Fprintf(os.Stderr, "Usage: %s dotted-ip-addr\n", os.Args[0])
os.Exit(1)
}
dotAddr := os.Args[1]

addr := net.ParseIP(dotAddr)
if addr == nil {
fmt.Println("Invalid address")
os.Exit(1)
}
mask := addr.DefaultMask()
network := addr.Mask(mask)
ones, bits := mask.Size()
fmt.Println("Address is ", addr.String(),
" Default mask length is ", bits,
"Leading ones count is ", ones,
"Mask is (hex) ", mask.String(),
" Network is ", network.String())
os.Exit(0)
}

测试

1
2
3
$ go build .
$ ./net 127.0.0.1
Address is 127.0.0.1 Default mask length is 32 Leading ones count is 8 Mask is (hex) ff000000 Network is 127.0.0.0