On Mon, 29 Jul 2024 19:26:28 +0530
Danish Prakash
Hi Stefano,
I was caught up with some work last month, hence the delay in responses since my last email.
On 5/24/24 11:09 PM, Stefano Brivio wrote:
+ if (sethostname(hostname, strlen(hostname)))
So, I mentioned before that you don't really need to set a NULL terminating byte for sethostname() itself, because it takes a length.
But strlen() needs it. If gethostname() truncated the hostname, according to POSIX, it's unspecified whether we'll have a NULL byte at the end of 'hostname', and strlen() would read out-of-bounds, past the end of 'hostname'.
That's not an issue with glibc, but if POSIX says it's not guaranteed, we shouldn't take anything for granted.
I would suggest that you simply add a NULL byte at HOST_NAME_MAX, unconditionally, that should cover the normal case as well as the ENAMETOOLONG case. I haven't tested this by the way.
Did you mean explicitly setting the NULL byte to `hostname`?
hostname[HOST_NAME_MAX] = '\0';
Yes, exactly.
Doing that after gethostname() and before sethostname() yields the desired result. I tested a few cases, seems to be fine.
Yes, I don't expect any difference with glibc, but better safe than sorry (with other C libraries). Thanks. -- Stefano