summaryrefslogtreecommitdiff
path: root/src/net.c
blob: 02c3d6ead3498aa4e7a459f89ad0c96f5a331c00 (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
52
53
54
55
56
57
58
59
60
#include <stdio.h>
#include <stdarg.h>
#include <stdbool.h>
#include <string.h>

#include <net/if.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>


int sockprintf(int s, const char *fmt, ...) {
	int     n;
	char    buf[8192] = {0};
	va_list vl;

	va_start(vl, fmt);
	n = vsnprintf(buf, sizeof(buf), fmt, vl);
	va_end(vl);

	return send(s, buf, n, 0);
}

bool validate_ipv4(const char *ip) {
	return inet_aton(ip, NULL) ? true : false;
}

bool validate_ip(const char *ip) {
	struct in_addr  addr4;
	struct in6_addr addr6;

	return inet_pton(AF_INET, ip, &addr4) == 1 || inet_pton(AF_INET6, ip, &addr6) == 1;
}

// get the interface assigned to the default route. this is a sensible
// default for most deployments, but not perfect.
char *get_default_iface(void) {
	static char iface[IFNAMSIZ] = {0};
	FILE *fp = fopen("/proc/net/route", "r");
	if (!fp) {
		return NULL;
	}

	char line[256];
	fgets(line, sizeof(line), fp); // skip header line
	while (fgets(line, sizeof(line), fp)) {
		char iface_name[IFNAMSIZ];
		unsigned long dest;
		if (sscanf(line, "%s %lx", iface_name, &dest) == 2) {
			if (dest == 0) { // default route
				strncpy(iface, iface_name, IFNAMSIZ - 1);
				fclose(fp);
				return iface;
			}
		}
	}

	fclose(fp);
	return NULL;
}