Skip to content

Instantly share code, notes, and snippets.

@schors
Created November 10, 2019 14:06
Show Gist options
  • Save schors/79f6d7d06f6ae9b50906c0efae74e30d to your computer and use it in GitHub Desktop.
Save schors/79f6d7d06f6ae9b50906c0efae74e30d to your computer and use it in GitHub Desktop.
Convert string with IPv4 address to int32 in GO language
// my IPv4 parser without slices
func ip2i(s string) uint32 {
var ip, n uint32 = 0, 0
var r uint = 24
for i := 0; i < len(s); i++ {
if '0' <= s[i] && s[i] <= '9' {
n = n*10 + uint32(s[i]-'0')
if n > 0xFF {
//Debug.Printf("Bad IP (1) n=%d: %s\n", n, s)
return 0xFFFFFFFF
}
} else if s[i] == '.' {
if r != 0 {
ip = ip + (n << r)
} else {
//Debug.Printf("Bad IP (2): %s\n", s)
return 0xFFFFFFFF
}
r = r - 8
n = 0
} else {
//Debug.Printf("Bad IP (3): %s\n", s)
return 0xFFFFFFFF
}
}
if r != 0 {
//Debug.Printf("Bad IP (4): %s\n", s)
return 0xFFFFFFFF
}
ip = ip + n
return ip
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment