]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/ether-addr-util.c
pkgconfig: define variables relative to ${prefix}/${rootprefix}/${sysconfdir}
[thirdparty/systemd.git] / src / basic / ether-addr-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <errno.h>
4 #include <net/ethernet.h>
5 #include <stdio.h>
6 #include <sys/types.h>
7
8 #include "ether-addr-util.h"
9 #include "macro.h"
10 #include "string-util.h"
11
12 char* ether_addr_to_string(const struct ether_addr *addr, char buffer[ETHER_ADDR_TO_STRING_MAX]) {
13 assert(addr);
14 assert(buffer);
15
16 /* Like ether_ntoa() but uses %02x instead of %x to print
17 * ethernet addresses, which makes them look less funny. Also,
18 * doesn't use a static buffer. */
19
20 sprintf(buffer, "%02x:%02x:%02x:%02x:%02x:%02x",
21 addr->ether_addr_octet[0],
22 addr->ether_addr_octet[1],
23 addr->ether_addr_octet[2],
24 addr->ether_addr_octet[3],
25 addr->ether_addr_octet[4],
26 addr->ether_addr_octet[5]);
27
28 return buffer;
29 }
30
31 int ether_addr_compare(const void *a, const void *b) {
32 assert(a);
33 assert(b);
34
35 return memcmp(a, b, ETH_ALEN);
36 }
37
38 static void ether_addr_hash_func(const void *p, struct siphash *state) {
39 siphash24_compress(p, sizeof(struct ether_addr), state);
40 }
41
42 const struct hash_ops ether_addr_hash_ops = {
43 .hash = ether_addr_hash_func,
44 .compare = ether_addr_compare
45 };
46
47 int ether_addr_from_string(const char *s, struct ether_addr *ret) {
48 size_t pos = 0, n, field;
49 char sep = '\0';
50 const char *hex = HEXDIGITS, *hexoff;
51 size_t x;
52 bool touched;
53
54 #define parse_fields(v) \
55 for (field = 0; field < ELEMENTSOF(v); field++) { \
56 touched = false; \
57 for (n = 0; n < (2 * sizeof(v[0])); n++) { \
58 if (s[pos] == '\0') \
59 break; \
60 hexoff = strchr(hex, s[pos]); \
61 if (!hexoff) \
62 break; \
63 assert(hexoff >= hex); \
64 x = hexoff - hex; \
65 if (x >= 16) \
66 x -= 6; /* A-F */ \
67 assert(x < 16); \
68 touched = true; \
69 v[field] <<= 4; \
70 v[field] += x; \
71 pos++; \
72 } \
73 if (!touched) \
74 return -EINVAL; \
75 if (field < (ELEMENTSOF(v)-1)) { \
76 if (s[pos] != sep) \
77 return -EINVAL; \
78 else \
79 pos++; \
80 } \
81 }
82
83 assert(s);
84 assert(ret);
85
86 s += strspn(s, WHITESPACE);
87 sep = s[strspn(s, hex)];
88
89 if (sep == '.') {
90 uint16_t shorts[3] = { 0 };
91
92 parse_fields(shorts);
93
94 if (s[pos] != '\0')
95 return -EINVAL;
96
97 for (n = 0; n < ELEMENTSOF(shorts); n++) {
98 ret->ether_addr_octet[2*n] = ((shorts[n] & (uint16_t)0xff00) >> 8);
99 ret->ether_addr_octet[2*n + 1] = (shorts[n] & (uint16_t)0x00ff);
100 }
101
102 } else if (IN_SET(sep, ':', '-')) {
103 struct ether_addr out = ETHER_ADDR_NULL;
104
105 parse_fields(out.ether_addr_octet);
106
107 if (s[pos] != '\0')
108 return -EINVAL;
109
110 for (n = 0; n < ELEMENTSOF(out.ether_addr_octet); n++)
111 ret->ether_addr_octet[n] = out.ether_addr_octet[n];
112
113 } else
114 return -EINVAL;
115
116 return 0;
117 }