C: inet_ntop return值位置?

C: inet_ntop return value position?

我正在查看 inet_ntop 文档。通常,C return 中的字符串生成器操作要么是指向字符串末尾的指针,要么是指示写入的字符串长度的整数。

inet_ntop 的文档表述相当含糊:

On success, inet_ntop() returns a non-null pointer to dst.  NULL is 
returned if there was an error, with the errno set to indicate the 
error.

这里有两个问题:

  1. 空字符串终止:不清楚我是否需​​要在整个内存分配中添加空字符串定界符,其中 inet_ntop 在 3 或更多顺序编译时正在打印

  2. 我不知道函数return的输出是指向最后一个写入字符的指针,还是指向第一个写入字符的指针。


inet_ntopreturn是什么意思?

我很清楚,但也许你需要应用一些 "good will" 才能得到它:

  1. 如果没有终止就不是C中的字符串,所以结果当然是终止了。
  2. dst是输入参数,虽然写的有点怪"a pointer to dst"也不可能是"a pointer to dst plus something".

你当然也可以read an implementation看看发生了什么。 IPv4 和 v6 变体的 "happy path"(无缓冲区溢出)的最后一个语句是:

return strcpy(dst, tmp);

这会立即告诉您 dst 正在接收一个终止的字符串,并且返回 dst

它 returns const char * 并且由于 dst 参数必须是有效对象(您不能将 NULL 作为 dst 传递)无需创建指向 return 函数状态的中间指针。

inet_pton() documentation:

...

SYNOPSIS

#include <arpa/inet.h>

const char *inet_ntop(int af, const void *restrict src,
       char *restrict dst, socklen_t size);

...

DESCRIPTION

The inet_ntop() function shall convert a numeric address into a text string suitable for presentation. The af argument shall specify the family of the address. This can be AF_INET or AF_INET6. The src argument points to a buffer holding an IPv4 address if the af argument is AF_INET, or an IPv6 address if the af argument is AF_INET6; the address must be in network byte order. The dst argument points to a buffer where the function stores the resulting text string; it shall not be NULL. The size argument specifies the size of this buffer, which shall be large enough to hold the text string (INET_ADDRSTRLEN characters for IPv4, INET6_ADDRSTRLEN characters for IPv6).

...

RETURN VALUE

The inet_ntop() function shall return a pointer to the buffer containing the text string if the conversion succeeds, and NULL otherwise, and set errno to indicate the error.

...

ERRORS

The inet_ntop() and inet_pton() functions shall fail if:

[EAFNOSUPPORT] The af argument is invalid.

[ENOSPC] The size of the inet_ntop() result buffer is inadequate.

the definition of a "string"

3.92 Character String

A contiguous sequence of characters terminated by and including the first null byte.

鉴于此,

的答案
  1. Null string termination: it is not clear whether I need to add a null string delimiter throughout the memory allocation where inet_ntop is printing when compiling at order 3 or more

应该清楚了。根据定义,字符串包含空字节。 inet_pton() returns 指向包含此类字符串的缓冲区的指针。不需要添加空字节。

以及

的答案
  1. I do not know whether the output of the function returns a pointer to the last written character, or the first written character.

由C标准在6.3.2.3 Pointers, paragraph 7中给出:

... When a pointer to an object is converted to a pointer to a character type, the result points to the lowest addressed byte of the object.

因此,inet_ntop()返回的"pointer to the buffer containing the text string if the conversion succeeds"指向字符串中的第一个字节。