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.

  • 写回答

1条回答 默认 最新

  • dongmubi4375 2018-03-06 23:30
    关注

    It looks like they're using a representation that allows them to easily handle both IPv4 and IPv6 addresses with the same code. They're using a single 16-byte representation for either type of IP.

    The comments at the top of the code (that you linked to) explain in pretty clearly:

    // IPv4 addresses are 4 bytes; IPv6 addresses are 16 bytes.
    // An IPv4 address can be converted to an IPv6 address by
    // adding a canonical prefix (10 zeros, 2 0xFFs).
    // This library accepts either size of byte slice but always
    // returns 16-byte addresses.
    

    You can pass in either 4-byte or 16-byte representations of IPv4 addresses, but the library will internally use 16-byte ones and always return those.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体
  • ¥88 实在没有想法,需要个思路
  • ¥15 MATLAB报错输入参数太多
  • ¥15 python中合并修改日期相同的CSV文件并按照修改日期的名字命名文件
  • ¥15 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入