duanfu9523
2018-03-06 23:07
浏览 204
已采纳

为什么Go net.IPv4在内部创建16字节地址

I noticed Go creates a 16 byte internal representation of a 4 byte IPv4 Address when using:

// IPv4 returns the IP address (in 16-byte form) of the
// IPv4 address a.b.c.d.
func IPv4(a, b, c, d byte) IP {
    p := make(IP, IPv6len)
    copy(p, v4InV6Prefix)
    p[12] = a
    p[13] = b
    p[14] = c
    p[15] = d
    return p
}

https://golang.org/src/net/ip.go

Is there a reason that IPv4 is initially created with 16 bytes? I was doing some calculations for Broadcast and Networkaddress where I accessed the internal byte[] directly and got confused that I had to call To4() to do something like

start := binary.BigEndian.Uint32([]byte(ip))

and actually get the IPv4 Address as uint32.

图片转代码服务由CSDN问答提供 功能建议

我注意到Go在使用以下命令时会创建一个4字节IPv4地址的16字节内部表示形式:</ p>

  // IPv4返回IP地址(以16字节形式)
 // IPv4地址abcd 
func IPv4(a,b,c,d字节)IP {
p:=  make(IP,IPv6len)
复制(p,v4InV6Prefix)
p [12] = a 
p [13] = b 
p [14] = c 
p [15] = d 
 return p 
} \  n </ code> </ pre> 
 
 

https:// golang。 org / src / net / ip.go </ p>

是否有最初创建16个字节的IPv4的原因? 我在进行广播和网络地址的一些计算时,直接访问了内部byte []并感到困惑,不得不调用 To4()</ code>来进行类似</ p>

  start:= binary.BigEndian.Uint32([] byte(ip))
 </ code> </ pre> 
 
 

,实际上将IPv4地址获取为uint32。</ p> </ div>

1条回答 默认 最新

相关推荐 更多相似问题