net.ParseIPv4Mask(s string)

2,741 views
Skip to first unread message

Rio

unread,
Mar 18, 2014, 3:19:48 PM3/18/14
to golan...@googlegroups.com
I want to add a function `ParseIPv4Mask` to the `net` package. Here is what I have: 

// Parse IPv4 netmask written in IP form (e.g. "255.255.255.0").
func ParseIPv4Mask(s string) IPMask {
mask := parseIPv4(s)
if mask == nil {
return nil
}
return IPv4Mask(mask[12], mask[13], mask[14], mask[15])
}


The reason is that in many use cases we still use IPv4 network mask in IP form instead of CIDR, but the `net` package does not provide a simple and easy way to parse it.

I wanted to change the return value of net.IPMask.String() to be IP form too, but that will break backward-compatiblity so that's a no go. A work around is to write `net.IP(ipmask).String()` instead.

Ian Lance Taylor

unread,
Mar 18, 2014, 4:38:53 PM3/18/14
to Rio, golang-nuts
Given that IPv4 netmasks are kind of out of date these days, and given
that the code to parse them is pretty simple--you wrote it right
there, at least if you use net.ParseIP--I'm not sure this warrants
being in the net package.

Ian

Riobard Zhan

unread,
Mar 18, 2014, 6:00:25 PM3/18/14
to Ian Lance Taylor, golang-nuts
On Tue, Mar 18, 2014 at 6:08 PM, Ian Lance Taylor <ia...@golang.org> wrote:
>
> Given that IPv4 netmasks are kind of out of date these days, and given
> that the code to parse them is pretty simple--you wrote it right
> there, at least if you use net.ParseIP--I'm not sure this warrants
> being in the net package.


I wouldn't say IPv4 net masks are out of date now. From my experience
with various OS and network tools I would actually say they are more
popular than CIDR forms (which is quite unfortunate as CIDR is better
IMHO). Just an example: the latest versions of OS X 10.9, Windows 8,
and Ubuntu 13.10 all require net masks in its network configurations.

The parsing code is indeed very simple, however it relies on the
implementation of net.IP type. Quick test: without checking the source
code of the net package, how many users would be able to tell the
difference between net.IP and net.IPMask, given that the doc for
net.IPMask states that “an IP mask is an IP address?” I would not be
surprised if people write this instead:

// Parse IPv4 netmask written in IP form (e.g. "255.255.255.0").
func ParseIPv4Mask(s string) net.IPMask {
return net.IPMask(net.ParseIP(s))
}

The code above is wrong. Go figure.

Given the popularity of net masks and the fact that implementation of
the standard library is not guaranteed to stay the same (only exposed
interfaces and functions are promised to be backward-compatiblie
between major versions IIRC?), I think it's better to add this little
function to the `net` package instead of asking people to rely on a
leaky abstraction.
Reply all
Reply to author
Forward
0 new messages