为什么在Golang中,DefaultMask()方法的接收者类型是IP?

huangapple go评论87阅读模式
英文:

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

问题

我正在查看Golang源代码这里,在net包下的DefaultMask()函数中,我不明白为什么这个函数不是一个包函数(没有接收者),所以从我的角度来看,正确的调用应该是:

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

而不是:

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

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(&quot;192.168.1.1&quot;)
    i := ip.Mask(net.DefaultMask()) // &lt;---- 

instead of the :

	ip := net.ParseIP(&quot;192.168.1.1&quot;)
    i := ip.Mask(ip.DefaultMask()) &lt;----

答案1

得分: 6

IPv4的默认子网掩码与分类IPv4分配有关,这主要是一个历史遗留问题。

A类IP地址范围是从0.0.0.0到127.255.255.255,B类是从128.0.0.0到191.255.255.255,C类是从192.0.0.0到223.255.255.255。因此,可以通过查看IP地址的第一个段来确定其类别掩码。这就是为什么DefaultMask()需要一个IP地址作为参数。

例如,IP地址192.168.1.1是C类地址,因此它的默认子网掩码是255.255.255.0。

在互联网上,类别掩码是无关紧要的,因为互联网上只使用无类别域间路由(CIDR)(以及IPv6)。

英文:

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).

答案2

得分: 2

你可以看到,如果查看源代码,就能明白为什么需要知道类别:

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

这段代码需要根据 IP 地址的第一个字节来确定所属的类别。

英文:

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

switch {
	case ip[0] &lt; 0x80:
		return classAMask
	case ip[0] &lt; 0xC0:
		return classBMask
	default:
		return classCMask
	}

huangapple
  • 本文由 发表于 2021年12月14日 00:09:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/70337602.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定