Skip to content

Instantly share code, notes, and snippets.

@JayGoldberg
Last active May 12, 2019 12:50
Show Gist options
  • Save JayGoldberg/4a2a0d159342e53434f2785d7c9cbec5 to your computer and use it in GitHub Desktop.
Save JayGoldberg/4a2a0d159342e53434f2785d7c9cbec5 to your computer and use it in GitHub Desktop.
determines if a string is a valid IPv4 address in golang, but the correct way to do this is to use net.ParseIP() and check for err
package main
import (
"fmt"
"strconv"
)
import "strings"
func is_ipv4(host string) bool {
parts := strings.Split(host, ".")
if len(parts) < 4 {
return false
}
for _,x := range parts {
if i, err := strconv.Atoi(x); err == nil {
if i < 0 || i > 255 {
return false
}
} else {
return false
}
}
return true
}
func main() {
addresses := []string{"192.168.1.1", "10.addr.3.4"}
for _, address := range addresses {
if is_ipv4(address) {
fmt.Println("This is a valid IPv4 address")
continue
}
fmt.Println("This is NOT a valid IPv4 address")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment