Skip to content

Instantly share code, notes, and snippets.

@stokito
Created October 16, 2021 07:15
Show Gist options
  • Save stokito/775f40c1af54a1bc5d699e374e5df687 to your computer and use it in GitHub Desktop.
Save stokito/775f40c1af54a1bc5d699e374e5df687 to your computer and use it in GitHub Desktop.
Check that string is an IP address
// IsIp checks that the given string is IPv4 or IPv6 address.
func IsIp(addr string) bool {
// IPv6
if addr[0] == '[' {
return true
}
// domain can have digits, but it can't have ONLY digits
// So if all symbols are digits then this is an IPv4 address. We can check only first octet before dot .
// end = min(addr len,3)
end := len(addr)
if end > 3 {
end = 3
}
for k := 0; k < end ; k++ {
char := addr[k]
if char == '.' {
break
}
// if not digit then this is not an IP
if char < '0' || char > '9' {
return false
}
}
return true
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment