Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

golang cast a string to net.IPNet type

Tags:

casting

go

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

like image 884
littleWicky Avatar asked Jun 11 '14 17:06

littleWicky


2 Answers

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)
    }
}
like image 140
fabrizioM Avatar answered Sep 28 '22 08:09

fabrizioM


I don't think you want casting; instead I think you want ParseCIDR

func ParseCIDR(s string) (IP, *IPNet, error)
like image 24
cnicutar Avatar answered Sep 28 '22 09:09

cnicutar