diff options
author | dzwdz | 2023-12-25 20:12:44 +0100 |
---|---|---|
committer | dzwdz | 2023-12-25 20:12:44 +0100 |
commit | 4be1fd62131f7e186e6f92f1bb5a356dc1ac1951 (patch) | |
tree | 54de3a2d99fe9d6e93ad45c5107aff5420f9900d /src/libc/net/gethostbyname.c | |
parent | b9f5f92bff69059471a76e73539780eedb356455 (diff) |
user/libc: reorganize net stuff, basic hosts-only gethostbyname()
/usr/share/hosts because i don't have /etc/ yet and i don't feel like creating it.
Diffstat (limited to 'src/libc/net/gethostbyname.c')
-rw-r--r-- | src/libc/net/gethostbyname.c | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/libc/net/gethostbyname.c b/src/libc/net/gethostbyname.c new file mode 100644 index 0000000..f2b59c1 --- /dev/null +++ b/src/libc/net/gethostbyname.c @@ -0,0 +1,51 @@ +#include <arpa/inet.h> +#include <ctype.h> +#include <netdb.h> +#include <netinet/in.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +struct hostent *gethostbyname(const char *name) { + // TODO ipv4 addresses should just get copied + static struct hostent he; + static struct in_addr addr; + static void *addrs[2] = {NULL, NULL}; + bool found = false; + char buf[256]; + FILE *fp; + + if (he.h_name) { + free(he.h_name); + he.h_name = NULL; + } + + if ((fp = fopen("/usr/share/hosts", "r")) == NULL) { + return NULL; + } + while (!found && fgets(buf, sizeof buf, fp)) { + char *s; + if (!isdigit(buf[0])) continue; + s = strtok(buf, " \t\n"); + if (!inet_aton(s, &addr)) continue; + while ((s = strtok(NULL, " \t\n"))) { + if (strcmp(s, name) == 0) { + found = true; + break; + } + } + } + fclose(fp); + if (!found) { + return NULL; + } + + he.h_name = strdup(name); + he.h_aliases = NULL; + he.h_addrtype = AF_INET; + he.h_length = 4; + he.h_addr_list = (void*)&addrs; + addrs[0] = &addr.s_addr; + return &he; +} |