How to check if a string is IPv4 or IPv6 or invalid in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "net"
)

func checkIPAddress(s string) string {
    ip := net.ParseIP(s)
    if ip == nil {
        return "Invalid"
    }

    if ip.To4() != nil {
        return "IPv4"
    }

    return "IPv6"
}

func main() {
    fmt.Println(checkIPAddress("112.128.1.2"))
    fmt.Println(checkIPAddress("2001:0dc7:85b2:0000:0000:6d3e:0380:8651"))
    fmt.Println(checkIPAddress("999.999.999.999"))
    fmt.Println(checkIPAddress("abc"))
}



/*
run:

IPv4
IPv6
Invalid
Invalid

*/

 



answered Jan 20 by avibootz

Related questions

...