为什么 inet_ntop() return 是指针而不是 int?

Why does inet_ntop() return a pointer instead of an int?

inet_ntop() 的签名如下:

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

描述:

   This function converts the network address structure src in the
   af address family into a character string.  The resulting string
   is copied to the buffer pointed to by dst, which must be a non-
   null pointer.  The caller specifies the number of bytes available
   in this buffer in the argument size.

   On success, inet_ntop() returns a non-null pointer to dst, or NULL
   if there was an error.

套接字操作的模式(例如,getsockopt()、socket()、bind()、listen()、connect() 等)通常是 return 一个 int,表示 (0 ) 成功,或 (-1) 错误。

inet_ntop() 到 return 指向调用者传递给它的数据结构的指针似乎是多余的 -- dst。显然,调用者已经知道该数据,因为需要将其传递给函数。必须有一些令人信服的理由才能脱离公约; return冗余信息肯定不是这样的。

我觉得很愚蠢,因为我没有看到这样做的原因。有什么见解吗?

虽然应该在委员会讨论记录中找到这些选择的原因,或者询问设计 API 的人,但我可以猜测一下。

inet_ntop() 是一个 POSIX 函数,因此它更多地来自 C 而不是来自 C++。正如您所说,套接字操作的模式是 return 和 int。但是 inet_ntop() 更像是一个字符串函数,所以我将它与 string.h 库中的函数进行比较。仅考虑

char *strcpy( char *dest, const char *src );

为什么 return 使用我传入的相同指针?对于不声明多个临时变量的链接操作:

char s[] = "this is the origial string I want to copy";
char *my_copy = strcpy(malloc(strlen(s) + 1), s);

(我知道这是不好的做法,因为我们没有检查 malloc 的 return 值,但我认为设计没有考虑到这一点)。

更多(真的更多)猜测工作可用 here

如果您想减少代码行数,它会很有用。您可以直接在 printf()、strcpy() 等中使用 return 值 ...