Debian Codegraph @

src/basic/af-list.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <string.h>
4 #include <sys/socket.h>
5
6 #include "af-list.h"
7 #include "string-util.h"
8
9 static const struct af_name* lookup_af(register const char *str, register GPERF_LEN_TYPE len);
10
11 #include "af-from-name.inc"
12 #include "af-to-name.inc"
13
14 const char* af_to_name(int id) {
15
16 if (id <= 0)
17 return NULL;
18
19 if ((size_t) id >= ELEMENTSOF(af_names))
20 return NULL;
21
22 return af_names[id];
23 }
24
25 const char* af_to_name_short(int id) {
26 const char *f;
27
28 if (id == AF_UNSPEC)
29 return "*";
30
31 f = af_to_name(id);
32 if (!f)
33 return "unknown";
34
35 assert(startswith(f, "AF_"));
36 return f + 3;
37 }
38
39 int af_from_name(const char *name) {
40 const struct af_name *sc;
41
42 assert(name);
43
44 sc = lookup_af(name, strlen(name));
45 if (!sc)
46 return -EINVAL;
47
48 return sc->id;
49 }
50
51 int af_max(void) {
52 return ELEMENTSOF(af_names);
53 }
54
55 const char* af_to_ipv4_ipv6(int id) {
56 /* Pretty often we want to map the address family to the typically used protocol name for IPv4 +
57 * IPv6. Let's add special helpers for that. */
58 return id == AF_INET ? "ipv4" :
59 id == AF_INET6 ? "ipv6" : NULL;
60 }
61
62 int af_from_ipv4_ipv6(const char *af) {
63 return streq_ptr(af, "ipv4") ? AF_INET :
64 streq_ptr(af, "ipv6") ? AF_INET6 : AF_UNSPEC;
65 }