Last active
May 12, 2019 12:50
-
-
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
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
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