summaryrefslogtreecommitdiff
path: root/src/libc/net/gethostbyname.c
blob: f2b59c128ac0ba2ea6283499c5bc800261ace896 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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;
}