Search code examples
clibpcapinetinet-ntop

C: inet_ntop return value position?


I am reviewing the inet_ntop documentation. Typically, string builder operations in C return either a pointer to the end of the string, or an integer indicating the length of the string written.

The documentation of inet_ntop states quite ambiguously:

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.

There are two problems here:

  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

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


What does inet_ntop return?


Solution

  • It's quite clear to me, but perhaps you need to apply some "good will" to get it:

    1. It's not a string in C if it isn't terminated, so of course the result is terminated.
    2. dst is an input argument, even if it's a bit weirdly written "a pointer to dst" can't be "a pointer to dst plus something".

    You can of course also read an implementation to see what's going on. The last statement for the "happy path" (no buffer overflow) for both IPv4 and v6 variants is:

    return strcpy(dst, tmp);
    

    Which instantly tells you that dst is receiving a terminated string, and that dst is returned.