golang cast a string to net.IPNet type
Asked Answered
C

3

7

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

Cosmopolis answered 11/6, 2014 at 17:34 Comment(0)
W
7

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)
    }
}
Wordsworth answered 11/6, 2014 at 17:43 Comment(2)
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.Cosmopolis
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.Blindfish
D
5

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

func ParseCIDR(s string) (IP, *IPNet, error)
Ditchwater answered 11/6, 2014 at 17:37 Comment(0)
P
0

This is how to do it using the IPAddress Go library. CIDR subnets, IP addresses and masks all use the same type in the IPAddress library, ipaddr.IPAddress, making code simpler. Disclaimer: I am the project manager.

package main

import (
    "fmt"
    "github.com/seancfoley/ipaddress-go/ipaddr"
    "net"
)

func main() {
    parseAddr("192.168.1.1/24")
    parseAddr("fd04:3e42:4a4e:3381::/64")
}

func parseAddr(cidrStr string) {
    cidr := ipaddr.NewIPAddressString(cidrStr)
    subnet, addr := cidr.GetAddress().ToPrefixBlock(), cidr.GetHostAddress()
    var ipNet = net.IPNet{
        IP:   subnet.GetNetIP(),
        Mask: subnet.GetNetworkMask().Bytes(),
    }
    fmt.Printf("\nsubnet: %s\naddress: %s\nIPNet: %+v\n", subnet, addr, ipNet)
}

Output:

subnet: 192.168.1.0/24
address: 192.168.1.1
IPNet: {IP:192.168.1.0 Mask:ffffff00}

subnet: fd04:3e42:4a4e:3381::/64
address: fd04:3e42:4a4e:3381::
IPNet: {IP:fd04:3e42:4a4e:3381:: Mask:ffffffffffffffff0000000000000000}
Pressor answered 3/7, 2022 at 16:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.