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
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)
}
}
I don't think you want casting; instead I think you want ParseCIDR
func ParseCIDR(s string) (IP, *IPNet, error)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With