将IPMask转换为IPAddr

将IPMask转换为IPAddr

问题描述:

I want to display an object of type net.IPMask in the same notation as net.IPAddr. I want to be able to do this for both IPv4 and IPv6 masks. For instance:

"fffffe00" ---> "255.255.254.0"

I could accomplish this by manually parsing the object of type net.IPMask. However, is there a way to accomplish this by converting an object of type net.IPMask to an object of type net.IPAddr, ideally using functions built in to the net package?

net.IPMask is just an IP address, so you can convert it to a net.IP and call its String() method to get a formatted IP address:

mask := net.CIDRMask(23, 32)
addr := net.IP(mask).String()

https://play.golang.org/p/A_oJfD8lpwP