Home > Software engineering >  Convert netip.Addr to net.IP for IPv4 address in Go
Convert netip.Addr to net.IP for IPv4 address in Go

Time:09-27

I have an IPv4 address as an netip.Addr (new package/type introduced with Go 1.18) https://pkg.go.dev/net/netip#Addr

I would like to convert my IPv4 address to net.IP type (https://pkg.go.dev/net#IP).

I already have 2 methods to convert my IPv4 from one type to another :

// ip is an netip.Addr 

var dst_ip net.IP

dst_ip := net.ParseIP(ip.String())

// or

dst_ip := net.IPv4(ip.As4()[0], ip.As4()[1], ip.As4()[2], ip.As4()[3])

Is there a more efficient way to do this type conversion ?

CodePudding user response:

Here is an example how you could do this more efficient, as net.IP underlying type is bytes we are able to cast []byte to net.IP type:

package main

import (
    "fmt"
    "net"
    "net/netip"
)

func main() {
    // example Addr type
    addr, err := netip.ParseAddr("10.0.0.1")
    fmt.Println(addr, err)

    // get Addr as []byte
    s := addr.AsSlice()
    // cast bytes slice to net.IP (it works as net.IP underlying type is also []byte so net.IP and []byte are identical)
    ip := net.IP(s)
    fmt.Println(ip.IsPrivate())

    // lets see if everything works creating netip.Addr from net.IP (here you can also see how types work as netip.AddrFromSlice accepts []byte)
    addrFromIp, ok := netip.AddrFromSlice(ip)
    fmt.Println(addrFromIp, ok)
}

Playground link: https://go.dev/play/p/JUAMNHhdxUj

  • Related