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
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)
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}
© 2022 - 2024 — McMap. All rights reserved.