Reputation: 2512
I'm looking for a way to convert a netmask string into CIDR notation in Go.
For instance, "255.255.255.0" -> "/24"
I'm currently obtaining an IP address and the net mask string with the below logic, which may just be complicating things.
I've been perusing the net
library trying to see if there is a different function to use to accomplish what I'd like, which is really just a IP address in CIDR notation:
192.168.1.2/24
var mgmtInterface *net.Interface
var err error
mgmtInterface, err = net.InterfaceByName("eth0")
if err != nil {
log.Println("Unable to find interface eth0, trying en0")
mgmtInterface, err = net.InterfaceByName("en0")
}
addrs, err := mgmtInterface.Addrs()
if err != nil {
log.Println("interface has no address")
}
for _, addr := range addrs {
var ip net.IP
var mask net.IPMask
switch v := addr.(type) {
case *net.IPNet:
ip = v.IP
mask = v.Mask
case *net.IPAddr:
ip = v.IP
mask = ip.DefaultMask()
}
if ip == nil {
continue
}
ip = ip.To4()
if ip == nil {
continue
}
// create the netmask
cleanMask := fmt.Sprintf("%d.%d.%d.%d", mask[0], mask[1], mask[2], mask[3])
}
Upvotes: 3
Views: 5699
Reputation: 4615
This is straightforward using the IPAddress Go library. Note that this code works equally well with both IPv4 and IPv6. Disclaimer: I am the project manager.
import (
"fmt"
"github.com/seancfoley/ipaddress-go/ipaddr"
)
func main() {
maskStr := "255.255.255.0"
pref := ipaddr.NewIPAddressString(maskStr).GetAddress().
GetBlockMaskPrefixLen(true)
fmt.Printf("prefix length for %s is %d", maskStr, pref.Len())
}
Output:
prefix length for 255.255.255.0 is 24
Upvotes: 0
Reputation: 51632
This isn't very obvious at first, but:
addr := ip.To4()
sz, _ := net.IPV4Mask(addr[0], addr[1], addr[2], addr[3]).Size()
Upvotes: 6
Reputation: 3537
I'm not aware about existense of such function but it's easy to create one.
CIDR notation is just a count of set bits in netmask.
So, crude solution could be:
func cidr(netmask string) int {
var mask uint32
for idx, dotpart := range strings.Split(netmask, ".") {
part, _ := strconv.Atoi(dotpart)
mask = mask | uint32(part) << uint32(24-idx*8)
}
return len(fmt.Sprintf("%b", mask))
}
Upvotes: 0