golang cast a string to net.IPNet type

12,517

Solution 1

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)
    }
}

Solution 2

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

func ParseCIDR(s string) (IP, *IPNet, error)
Share:
12,517
Admin
Author by

Admin

Updated on June 18, 2022

Comments

  • Admin
    Admin about 2 years

    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

  • Admin
    Admin about 10 years
    This is pretty close to what I need. Ultimately I need to have the network and check to see if an ip is that network. I want to store this string as net.IPNet and then check against that type. my struct looks like type IpData struct { ShortDesc string LongDesc string Subnet net.IPNet Note string } I then have a slice of struct that I need to iterate my passed in ip against the Subnet.
  • David
    David over 8 years
    Do note that ParseCIDR returns IPNet as a pointer, so depending on how you use the result, you may have to dereference it, if the usage calls for the non-pointer version, so it would be *ipnet in the example above, when referring to the variable's value.