Skip to content

Instantly share code, notes, and snippets.

@alexpts
Last active October 11, 2020 05:45
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 alexpts/5c43d1c30739b883215cde4bc0cb1d30 to your computer and use it in GitHub Desktop.
Save alexpts/5c43d1c30739b883215cde4bc0cb1d30 to your computer and use it in GitHub Desktop.
parseIpv4
func parseIpv4(s string) [4]byte {
var ip [4]byte
// первые три байта парсим
for i := 0; i < 3; i++ {
for p := 0; p < 4; p++ {
if s[p] == '.' {
number, _ := strconv.ParseUint(s[:p], 10, 8)
ip[i] = byte(number)
s = s[p+1:]
break
}
}
}
// парсим оставшийся четвертый байт
number, _ := strconv.ParseUint(s, 10, 8)
ip[3] = byte(number)
return ip
}
// более медленный вариант на стандартном пакете net
func netParseIpv4(s string) [4]byte {
ip := net.ParseIP(s)
var ipBytes [4]byte
copy(ipBytes[:], ip[12:])
return ipBytes
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment