]> Sergey Matveev's repositories - btrtrc.git/blob - iplist/cidr.go
Note that torrent.Reader is not concurrent-safe
[btrtrc.git] / iplist / cidr.go
1 package iplist
2
3 import (
4         "bufio"
5         "io"
6         "net"
7 )
8
9 func ParseCIDRListReader(r io.Reader) (ret []Range, err error) {
10         s := bufio.NewScanner(r)
11         for s.Scan() {
12                 err = func() (err error) {
13                         _, in, err := net.ParseCIDR(s.Text())
14                         if err != nil {
15                                 return
16                         }
17                         ret = append(ret, Range{
18                                 First: in.IP,
19                                 Last:  IPNetLast(in),
20                         })
21                         return
22                 }()
23                 if err != nil {
24                         return
25                 }
26         }
27         return
28 }
29
30 // Returns the last, inclusive IP in a net.IPNet.
31 func IPNetLast(in *net.IPNet) (last net.IP) {
32         n := len(in.IP)
33         if n != len(in.Mask) {
34                 panic("wat")
35         }
36         last = make(net.IP, n)
37         for i := 0; i < n; i++ {
38                 last[i] = in.IP[i] | ^in.Mask[i]
39         }
40         return
41 }