-
Notifications
You must be signed in to change notification settings - Fork 140
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #193 from ipinfo/talhahameed/be-2715-handle-adjace…
…nt-prefixes-in-ipinfo-tool-aggregate Handle adjacent prefixes in ipinfo tool aggregate
- Loading branch information
Showing
3 changed files
with
148 additions
and
125 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
package lib | ||
|
||
import ( | ||
"bytes" | ||
"encoding/binary" | ||
"math" | ||
"net" | ||
"sort" | ||
) | ||
|
||
// CIDR represens a Classless Inter-Domain Routing structure. | ||
type CIDR struct { | ||
IP net.IP | ||
Network *net.IPNet | ||
} | ||
|
||
// newCidr creates a newCidr CIDR structure. | ||
func newCidr(s string) *CIDR { | ||
ip, ipnet, err := net.ParseCIDR(s) | ||
if err != nil { | ||
panic(err) | ||
} | ||
return &CIDR{ | ||
IP: ip, | ||
Network: ipnet, | ||
} | ||
} | ||
|
||
func (c *CIDR) String() string { | ||
return c.Network.String() | ||
} | ||
|
||
// MaskLen returns a network mask length. | ||
func (c *CIDR) MaskLen() uint32 { | ||
i, _ := c.Network.Mask.Size() | ||
return uint32(i) | ||
} | ||
|
||
// PrefixUint32 returns a prefix. | ||
func (c *CIDR) PrefixUint32() uint32 { | ||
return binary.BigEndian.Uint32(c.IP.To4()) | ||
} | ||
|
||
// Size returns a size of a CIDR range. | ||
func (c *CIDR) Size() int { | ||
ones, bits := c.Network.Mask.Size() | ||
return int(math.Pow(2, float64(bits-ones))) | ||
} | ||
|
||
// list returns a slice of sorted CIDR structures. | ||
func list(s []string) []*CIDR { | ||
out := make([]*CIDR, 0) | ||
for _, c := range s { | ||
out = append(out, newCidr(c)) | ||
} | ||
sort.Sort(cidrSort(out)) | ||
return out | ||
} | ||
|
||
type cidrSort []*CIDR | ||
|
||
func (s cidrSort) Len() int { return len(s) } | ||
func (s cidrSort) Swap(i, j int) { s[i], s[j] = s[j], s[i] } | ||
|
||
func (s cidrSort) Less(i, j int) bool { | ||
cmp := bytes.Compare(s[i].IP, s[j].IP) | ||
return cmp < 0 || (cmp == 0 && s[i].MaskLen() < s[j].MaskLen()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters