Search code examples
castinggo

golang cast a string to net.IPNet type


I have a slice of strings that are in CIDR notation. They are both ipv4 and ipv6 and I need them cast into the type net.IPNet.

How would I do this in golang?

example strings:

192.168.1.1/24
fd04:3e42:4a4e:3381::/64


Solution

  • As cnicutar says use net.ParseCIDR.

    This is a working example on how to actually use it.

    http://play.golang.org/p/Wtqy56LS2Y

    package main
    
    import (
        "fmt"
        "net"
    )
    
    func main() {
        ipList := []string{"192.168.1.1/24", "fd04:3e42:4a4e:3381::/64"}
        for i := 0; i < len(ipList); i += 1 {
            ip, ipnet, err := net.ParseCIDR(ipList[i])
            if err != nil {
                fmt.Println("Error", ipList[i], err)
                continue
            }
            fmt.Println(ipList[i], "-> ip:", ip, " net:", ipnet)
        }
    }