Skip to content

Instantly share code, notes, and snippets.

@JayGoldberg
Last active August 17, 2025 03:31
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 {
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)
}
}
@xXREDSTONEXx
Copy link

should be len(parts) != 4, "1.1.1.1.1.1" for example is passed by this func

@JayGoldberg
Copy link
Author

JayGoldberg commented Aug 17, 2025

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"

@JayGoldberg
Copy link
Author

ok figured out what line. fixed and added output of the tested addresses and a few extra test cases

@JayGoldberg
Copy link
Author

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