Skip to content

Instantly share code, notes, and snippets.

@azubkokshe
Created October 20, 2023 09:14
Show Gist options
  • Save azubkokshe/1349a122b5d2d1743134330f1c165ea6 to your computer and use it in GitHub Desktop.
Save azubkokshe/1349a122b5d2d1743134330f1c165ea6 to your computer and use it in GitHub Desktop.
matchIPv4Subnet
package main
import (
"testing"
)
func matchIPv4Subnet(addr, cidrAddr, prefix uint32) bool {
var mask uint32
if prefix >= 32 {
mask = 0xffffffff
} else {
mask = ^(0xffffffff >> prefix)
}
return (addr & mask) == (cidrAddr & mask)
}
func BenchmarkIPSubnetComparison(b *testing.B) {
subnets := []struct {
cidrAddr uint32
prefix uint32
}{
{0x5B6B3800, 22}, // 91.108.56.0/22
{0x5B6B0400, 22}, // 91.108.4.0/22
{0x5B6B0800, 22}, // 91.108.8.0/22
{0x5B6B1000, 22}, // 91.108.16.0/22
{0x5B6B0C00, 22}, // 91.108.12.0/22
{0x959AA000, 20}, // 149.154.160.0/20
{0x5B69C000, 23}, // 91.105.192.0/23
{0x5B6B1400, 22}, // 91.108.20.0/22
{0xB94C9700, 24}, // 185.76.151.0/24
}
addr := uint32(0x5B6B3B64)
b.ResetTimer()
b.ReportAllocs()
for i := 0; i < b.N; i++ {
for _, subnet := range subnets {
matchIPv4Subnet(addr, subnet.cidrAddr, subnet.prefix)
}
}
}
func main() {
testing.Benchmark(BenchmarkIPSubnetComparison)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment