diff options
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; +} |