Last active
August 17, 2025 03:31
-
-
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 hidden or 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 { | |
| i, err := strconv.Atoi(x) | |
| if err != nil { // Check for the error first | |
| return false | |
| } | |
| if i < 0 || i > 255 { | |
| return false | |
| } | |
| } | |
| return true | |
| } | |
| func main() { | |
| addresses := []string{"192.168.1.1", "10.addr.3.4", "1.1.1", "1.r.4.5.3"} | |
| for _, address := range addresses { | |
| if is_ipv4(address) { | |
| fmt.Printf("%s: This is a valid IPv4 address\n", address) | |
| continue | |
| } | |
| fmt.Printf("%s: This is NOT a valid IPv4 address\n", address) | |
| } | |
| } |
ok let me think about it, not sure I understand off the top of my head. And I need to properly format this and add a few more test cases in addresses []string eg "1.1.1", "1.1.1.1.1.1", "1.t.1"
ok figured out what line. fixed and added output of the tested addresses and a few extra test cases
Also removed else to be more idiomatic
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
should be len(parts) != 4, "1.1.1.1.1.1" for example is passed by this func