Last active
October 11, 2020 05:45
-
-
Save alexpts/5c43d1c30739b883215cde4bc0cb1d30 to your computer and use it in GitHub Desktop.
parseIpv4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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