This commit is contained in:
Gerasimos (Makis) Maropoulos 2022-11-25 23:53:50 +02:00
commit d4122e9981
2 changed files with 31 additions and 7 deletions

View File

@ -4,7 +4,6 @@ import (
"bytes"
"net"
"strings"
"unsafe"
)
/* Based on:
@ -18,14 +17,9 @@ type IPRange struct {
End string `ini:"end" json:"end" yaml:"End" toml:"End"`
}
func unsafeCompare(a []byte, b string) int {
bb := *(*[]byte)(unsafe.Pointer(&b))
return bytes.Compare(a, bb)
}
// IPInRange reports whether a given IP Address is within a range given.
func IPInRange(r IPRange, ipAddress net.IP) bool {
return unsafeCompare(ipAddress, r.Start) >= 0 && unsafeCompare(ipAddress, r.End) < 0
return bytes.Compare(ipAddress, net.ParseIP(r.Start)) >= 0 && bytes.Compare(ipAddress, net.ParseIP(r.End)) <= 0
}
// IPIsPrivateSubnet reports whether this "ipAddress" is in a private subnet.

View File

@ -58,4 +58,34 @@ func TestIP(t *testing.T) {
if expected := "126.105.144.250"; expected != got {
t.Logf("expected addr to be found: %s but got: %s", expected, got)
}
addresses = []string{
"10.10.233.1",
"126.105.144.250",
"192.168.99.33",
"172.18.22.23",
"10.0.0.0",
"10.255.255.255",
}
got, ok = GetIPAddress(addresses, privateRanges)
if !ok {
t.Logf("expected addr to be matched")
}
if expected := "126.105.144.250"; expected != got {
t.Logf("expected addr to be found: %s but got: %s", expected, got)
}
addresses = []string{
"10.0.0.0",
"10.10.233.1",
"192.168.99.33",
"172.18.22.23",
}
got, ok = GetIPAddress(addresses, privateRanges)
if ok {
t.Logf("expected addr to not be matched")
}
}