-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
handle_mask.go
99 lines (86 loc) · 2.11 KB
/
handle_mask.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
package main
import (
"encoding/binary"
"fmt"
"log"
"net"
"net/http"
"strconv"
"strings"
)
func (s *server) handleMask() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
ipParam := r.PathValue("ip")
maskParam := r.PathValue("mask")
// todo: check with regex
m, err := strconv.Atoi(maskParam)
if err != nil {
msg := fmt.Sprintf("mask is not int: %s", maskParam)
log.Print(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
if m < 0 || m > 32 {
msg := fmt.Sprintf("invalid mask: %s", maskParam)
log.Print(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
_, ipv4Net, err := net.ParseCIDR(ipParam + "/" + maskParam)
if err != nil {
msg := fmt.Sprintf("invalid ip: %s", ipParam)
log.Print(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/plain")
fmt.Fprint(w, ipParam+"/"+maskParam+"\n\n")
// print IP with paddings to align with binary format
ipParts := strings.Split(ipParam, ".")
for i, part := range ipParts {
fmt.Fprintf(w, "%8s", part)
if i < len(ipParts)-1 {
fmt.Fprint(w, ".")
}
}
fmt.Fprint(w, "\n")
// print IP in binary format
for i, part := range ipParts {
p, err := strconv.Atoi(part)
if err != nil {
msg := fmt.Sprintf("invalid ip: %s", ipParam)
log.Print(msg)
http.Error(w, msg, http.StatusBadRequest)
return
}
binPart := fmt.Sprintf("%08b", p)
fmt.Fprint(w, binPart)
if i < len(ipParts)-1 {
fmt.Fprint(w, ".")
}
}
fmt.Fprint(w, "\n")
// print mask
for i := 0; i < m; i++ {
fmt.Fprint(w, "X")
if (i+1)%8 == 0 && i < m-1 {
fmt.Fprint(w, ".")
}
}
fmt.Fprint(w, "\n\n")
if m >= 16 {
// print all possible IPs
mask := binary.BigEndian.Uint32(ipv4Net.Mask)
start := binary.BigEndian.Uint32(ipv4Net.IP)
// find the final address
finish := (start & mask) | (mask ^ 0xffffffff)
// loop through addresses as uint32
for i := start; i <= finish; i++ {
// convert back to net.IP
ip := make(net.IP, 4)
binary.BigEndian.PutUint32(ip, i)
fmt.Fprintln(w, ip)
}
}
}
}