fix(userspace/libc): implement gethostname()

Signed-off-by: EnderIce2 <enderice2@protonmail.com>
This commit is contained in:
EnderIce2 2025-03-10 22:05:28 +00:00
parent 6b4faf9f78
commit 551853c5d6
No known key found for this signature in database
GPG Key ID: 2EE20AF089811A5A

View File

@ -23,6 +23,7 @@
#include <stdio.h> #include <stdio.h>
#include <string.h> #include <string.h>
#include <fennix/syscalls.h> #include <fennix/syscalls.h>
#include <fcntl.h>
export char *optarg; export char *optarg;
export int optind, opterr, optopt; export int optind, opterr, optopt;
@ -183,16 +184,30 @@ export long gethostid(void);
export int gethostname(char *name, size_t namelen) export int gethostname(char *name, size_t namelen)
{ {
if (namelen == 0) if (namelen == 0)
{
errno = EINVAL;
return -1; return -1;
char *hostname = getenv("HOSTNAME");
if (hostname)
{
strncpy(name, hostname, namelen);
return 0;
} }
strncpy(name, "localhost", namelen); int fd = open("/etc/hostname", O_RDONLY);
if (namelen < strlen("localhost") + 1) if (fd == -1)
{
errno = ENAMETOOLONG;
return -1; return -1;
int result = read(fd, name, namelen);
close(fd);
if (result == -1)
return -1;
for (int i = 0; i < namelen; i++)
{
if (name[i] == '\n' || name[i] == '\r')
name[i] = '\0';
else if (name[i] < ' ' || name[i] > '~')
name[i] = '\0';
} }
return 0; return 0;