summaryrefslogtreecommitdiff
path: root/utils.c
blob: 87ed0fe92d879a79e3980ae70610224c011be118 (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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include <stdlib.h>
#include <errno.h>
#include <stdint.h>
#include <limits.h>
#include <arpa/inet.h>

#include "main.h"
#include "utils.h"

uint16_t sockaddr_port(struct sockaddr_in46 *addr)
{
	switch (addr->storage.ss_family) {
	case AF_INET:
		return ntohs(addr->in4.sin_port);
	case AF_INET6:
		return ntohs(addr->in6.sin6_port);
	default:
		return 0;
	}
}

char *
sockaddr_to_str(struct sockaddr_in46 *addr, char *buf, size_t buflen)
{
	char abuf[ADDRSTRLEN];

	switch (addr->storage.ss_family) {
	case AF_INET:
		snprintf(buf, buflen, "AF_INET4 %s %u",
			 inet_ntop(addr->in4.sin_family, &addr->in4.sin_addr, abuf, sizeof(abuf)),
			 (unsigned)ntohs(addr->in4.sin_port));
		break;
	case AF_INET6:
		snprintf(buf, buflen, "AF_INET6 %s %u",
			 inet_ntop(addr->in6.sin6_family, &addr->in6.sin6_addr, abuf, sizeof(abuf)),
			 (unsigned)ntohs(addr->in6.sin6_port));
		break;
	default:
		snprintf(buf, buflen, "AF_UNKNOWN");
		break;
	}

	return buf;
}

int
strtou16_strict(const char *str, uint16_t *result)
{
	char *end;
	long val;

	if (!str)
		return -EINVAL;

	errno = 0;
	val = strtol(str, &end, 10);

	if (errno == ERANGE && (val == LONG_MAX || val == LONG_MIN))
		return -EINVAL;
	
	if (errno != 0 && val == 0)
		return -EINVAL;

	if (end == str)
		return -EINVAL;

	if (*end != '\0')
		return -EINVAL;

	if (val < 1 || val > UINT16_MAX)
		return -EINVAL;

	if (result)
		*result = val;
	return 0;
}