Debian Codegraph @

src/tun_cidr.c

raw symbols SCIP
1 /* librist. Copyright © 2026 SipRadius LLC. All right reserved.
2 * Author: Sergio Ammirata, Ph.D. <[email protected]>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7 #include "librist/tun.h"
8
9 #ifdef _WIN32
10 #include <winsock2.h>
11 #include <ws2tcpip.h>
12 #else
13 #include <arpa/inet.h>
14 #endif
15 #include <stdlib.h>
16 #include <string.h>
17
18 int rist_tun_parse_cidr(const char *cidr, char *ip_out, size_t ip_len, int *prefix_out)
19 {
20 const char *slash;
21 size_t ip_part_len;
22 int prefix;
23 int family;
24
25 if (!cidr || !ip_out || ip_len == 0 || !prefix_out)
26 return -1;
27
28 slash = strchr(cidr, '/');
29 if (!slash) {
30 if (strlen(cidr) >= ip_len)
31 return -1;
32 strncpy(ip_out, cidr, ip_len - 1);
33 ip_out[ip_len - 1] = '\0';
34 prefix = strchr(cidr, ':') ? 128 : 32;
35 } else {
36 ip_part_len = (size_t)(slash - cidr);
37 if (ip_part_len == 0 || ip_part_len >= ip_len)
38 return -1;
39 memcpy(ip_out, cidr, ip_part_len);
40 ip_out[ip_part_len] = '\0';
41 prefix = atoi(slash + 1);
42 }
43
44 if (strchr(ip_out, ':') != NULL)
45 family = AF_INET6;
46 else
47 family = AF_INET;
48
49 if (family == AF_INET6) {
50 struct in6_addr addr6;
51
52 if (inet_pton(AF_INET6, ip_out, &addr6) != 1)
53 return -1;
54 if (prefix < 0 || prefix > 128)
55 return -1;
56 } else {
57 struct in_addr addr4;
58
59 if (inet_pton(AF_INET, ip_out, &addr4) != 1)
60 return -1;
61 if (prefix < 0 || prefix > 32)
62 return -1;
63 }
64
65 *prefix_out = prefix;
66 return 0;
67 }