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 springboot 3.0 实现Security 6.x版本集成
  • ¥15 PHP-8.1 镜像无法用dockerfile里的CMD命令启动 只能进入容器启动,如何解决?(操作系统-ubuntu)
  • ¥15 请帮我解决一下下面六个代码
  • ¥15 关于资源监视工具的e-care有知道的嘛
  • ¥35 MIMO天线稀疏阵列排布问题
  • ¥60 用visual studio编写程序,利用间接平差求解水准网
  • ¥15 Llama如何调用shell或者Python
  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)