inet_ntop() has a signature as follows:
const char* inet_ntop(int af, const void* src, char* dst, socklen_t size);
Description:
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.
The pattern for socket operations (e.g., getsockopt(), socket(), bind(), listen(), connect(), etc.) is typically to return an int, indicating (0) success, or (-1) error.
It seems redundant for inet_ntop() to return a pointer to the very data structure that the caller passed into it -- dst. Obviously, that datum was already known by the caller, since it was required to be passed into the function. There has to be some compelling reason for this to step away from the convention; returning redundant information surely cannot be such.
I'm feeling pretty stupid for just not seeing the reason for this. Any insight?
CodePudding user response:
While the reason for these choices should be found in the minutes of the committee discussion, or asked to the people who designed the API, I can take a guess.
inet_ntop()
is a POSIX function, so it comes from C more than from C . As you say, the pattern for socket operations is to return an int
. But inet_ntop()
is more a string function, so I'd compare it with functions from the string.h
library. Just consider
char *strcpy( char *dest, const char *src );
Why returning the same pointer I passed in? For chaining operations without declaring multiple temporary variables:
char s[] = "this is the origial string I want to copy";
char *my_copy = strcpy(malloc(strlen(s) 1), s);
(I know that this is bad practice because we are not checking the return value of malloc
, but I don't think that the design was taking this into account).
More (really more) guess work is available here.
CodePudding user response:
It's useful if you want to reduce the number of code lines. You can use the return value directly in printf(), strcpy() etc ...