为什么 inet_ntoa 中的缓冲区大小是 18? [英] Why is the buffer size in inet_ntoa 18?

查看:80
本文介绍了为什么 inet_ntoa 中的缓冲区大小是 18?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我查看了 inet_ntoa 的实现,例如 thisthis,

I looked at the implementations of inet_ntoa like this and this,

我想知道为什么他们都分配了一个 18 个字符的缓冲区.

I am wondering why they both allocate a buffer of 18 characters.

如果我取最大长度的 IPv4 地址字符串:255.255.255.255 我需要的大小是:每个八位字节 3 个,点 3 个,空终止符 1 个.3*4+3+1 = 16.

If I take the maximum length IPv4 address string: 255.255.255.255 the size that I need is: 3 for each octet, 3 for dots and 1 for the null terminator. 3*4+3+1 = 16.

那为什么我们需要那两个额外的字符?

So why do we need those 2 extra characters?

来自第一个链接的 inet_ntoa 实现:

The inet_ntoa implementation from the first link:

static __thread char buffer[18];

char *
inet_ntoa (struct in_addr in)
{
  unsigned char *bytes = (unsigned char *) ∈
  __snprintf (buffer, sizeof (buffer), "%d.%d.%d.%d",
              bytes[0], bytes[1], bytes[2], bytes[3]);
  return buffer;
}

推荐答案

如果我取最大长度的 IPv4 地址字符串:255.255.255.255我需要的大小是:每个八位字节 3 个,点 3 个,空值 1 个终结者.3*4+3+1 = 16.

If I take the maximum length IPv4 address string: 255.255.255.255 the size that I need is: 3 for each octet, 3 for dots and 1 for the null terminator. 3*4+3+1 = 16.

那为什么我们需要那两个额外的字符?

So why do we need those 2 extra characters?

你的计算是正确的.只需要 16 个字节来存储 inet_ntoa() 生成的点分十进制地址字符串,包括它的终止符.相关文档和规范至少早在 POSIX.1 2004 就指定了当前格式,据我所知,还没有发布产生任何其他格式的实现,因此我们只能推测为什么某些实现提供额外的空间.可能性包括但不限于

Your computation is correct. Only sixteen bytes are needed for storing the dotted-decimal address string produced by inet_ntoa(), including its terminator. The relevant documentation and specifications specify the current format at least as far back as POSIX.1 2004, and as far as I am aware, no implementation has ever been released that produced any other format, so we can only speculate about why some implementations provide extra space. Possibilities include, but are not necessarily limited to

  • 打字错误或计算错误;
  • 缓冲区曾经(可能仍然)用于不止一件事,而其他用途需要更多字节;
  • 某些实现用于格式化结果的算法得益于有几个额外的字节可以使用;
  • 为 slop 空间提供了额外的字节,以减轻假设错误的影响.

今天在许多实现中观察到的相同的额外字节可能支持多用途缓冲区替代方案,但该观察结果也与在某些早期实现中出现的那些字节的任何解释一致,可能是 BSD,并从那里传播到许多后续.我倾向于支持后一种解释.

That the same extra bytes are observed today in many implementations may support the multi-use buffer alternative, but that observation is also consistent with any explanation for those bytes appearing in some early implementation, maybe BSD, and being propagated from there to many subsequent ones. I'm inclined to favor the latter explanation.

这篇关于为什么 inet_ntoa 中的缓冲区大小是 18?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆