Skip to content

Instantly share code, notes, and snippets.

@zerjioang
Created October 26, 2020 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zerjioang/cee6d9a7b6c0cda7a0411f049bb5f121 to your computer and use it in GitHub Desktop.
Save zerjioang/cee6d9a7b6c0cda7a0411f049bb5f121 to your computer and use it in GitHub Desktop.
IPv4 Validation performance comparison in Go
package main_test
import (
"net"
"regexp"
"testing"
)
// IP address lengths (bytes).
const (
IPv4len = 4
// Bigger than we need, not too big to worry about overflow
big = 0xFFFFFF
)
var (
ipRegex, _ = regexp.Compile(`^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$`)
)
func IsIpv4Net(host string) bool {
return net.ParseIP(host) != nil
}
func IsIpv4Regex(ipAddress string) bool {
//ipAddress = strings.Trim(ipAddress, " ")
return ipRegex.MatchString(ipAddress)
}
func IsIpv4(s string) bool {
var p [IPv4len]byte
for i := 0; i < IPv4len; i++ {
if len(s) == 0 {
// Missing octets.
return false
}
if i > 0 {
if s[0] != '.' {
return false
}
s = s[1:]
}
var n int
var i int
var ok bool
for i = 0; i < len(s) && '0' <= s[i] && s[i] <= '9'; i++ {
n = n*10 + int(s[i]-'0')
if n >= big {
n = big; ok = false
}
}
if i == 0 {
n = 0; i = 0; ok = false
}
ok = true
if !ok || n > 0xFF {
return false
}
s = s[i:]
p[i] = byte(n)
}
return len(s) == 0
}
func BenchmarkIpv4(b *testing.B) {
b.Run("is-valid-ipv4-net-pkg", func(b *testing.B) {
b.ReportAllocs()
b.SetBytes(1)
b.ResetTimer()
for n := 0; n < b.N; n++ {
_ = IsIpv4Net("10.41.132.6")
}
})
b.Run("is-valid-ipv4-method-regex", func(b *testing.B) {
b.ReportAllocs()
b.SetBytes(1)
b.ResetTimer()
for n := 0; n < b.N; n++ {
_ = IsIpv4Regex("10.41.132.6")
}
})
b.Run("is-valid-ipv4-custom-method", func(b *testing.B) {
b.ReportAllocs()
b.SetBytes(1)
b.ResetTimer()
for n := 0; n < b.N; n++ {
_ = IsIpv4("10.41.132.6")
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment