Home > database >  Why DefaultMask() method has a receiver of type of IP in Golang?
Why DefaultMask() method has a receiver of type of IP in Golang?

Time:12-14

I was looking into Golang source code here and DefaultMask() under the net package, what I don't understand is why this function is not a package function (without receiver) so from my perpective, proper call would be like:

    ip := net.ParseIP("192.168.1.1")
    i := ip.Mask(net.DefaultMask()) // <---- 
    

instead of the :

    ip := net.ParseIP("192.168.1.1")
    i := ip.Mask(ip.DefaultMask()) <----

CodePudding user response:

The IPv4 default mask has to do with classful IPv4 assignment - a historical thing mostly.

Class A IPs went from 0.0.0.0 to 127.255.255.255, Class B to 191.255.255.255, and Class C to 223.255.255.255. Hence the class mask could be determined simply by looking at the first segment of the IP address. This is why DefaultMask() takes an IP address.

For example the IP 192.168.1.1 is a Class C, hence it's default subnet mask is 255.255.255.0.

The class mask is irrelevant on the Internet as it uses CIDR exclusively (and IPv6).

CodePudding user response:

You can see why if you look at the source. It needs to know the class:

switch {
    case ip[0] < 0x80:
        return classAMask
    case ip[0] < 0xC0:
        return classBMask
    default:
        return classCMask
    }
  •  Tags:  
  • go
  • Related