ascii-chat
Binary v0.16.50-198-g78f51665f
Library lib/v0.3.2-2240-g78f51665f
Video chat in your terminal
Loading...
Searching...
No Matches
ip.c
Go to the documentation of this file.
1
6
7/* Storage capacities in elements; text buffers include the terminating NUL. */
8#define UTIL_IP_IP_TEMP_BUFFER_SIZE 256
9#define UTIL_IP_NETWORK_BUFFER_SIZE 64
10#define UTIL_IP_IP2_BUFFER_SIZE 64
11
13#include <ascii-chat/util/ip.h>
14#include <ascii-chat/util/url.h>
16#include <ascii-chat/common.h>
19#include <ascii-chat/log/log.h>
20#include <string.h>
21#include <stdio.h>
22#include <stdlib.h>
23#ifdef _WIN32
24#include <winsock2.h>
25#include <ws2tcpip.h>
26#else
27#include <arpa/inet.h>
28#include <netinet/in.h>
29#endif
30
31// Helper function to validate IPv4 address format
32int is_valid_ipv4(const char *ip) {
33 if (!ip) {
34 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: NULL");
35 return 0; // Invalid
36 }
37
38 size_t ip_len = strlen(ip);
39 if (ip_len == 0) {
40 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: empty string");
41 return 0; // Invalid
42 }
43
44 if (ip_len > 256) {
45 char ip_buffer[BUFFER_SIZE_SMALL];
46 SAFE_STRNCPY(ip_buffer, ip, sizeof(ip_buffer));
47 SET_ERRNO(ERROR_INVALID_PARAM, "Suspiciously long ip: %s", ip_buffer);
48 return 0; // Invalid
49 }
50
51 // Some platforms accept octets with leading zeros; reject ambiguous forms
52 // consistently before using the system parser for the remaining validation.
53 for (const char *p = ip; *p; ++p) {
54 if ((p == ip || p[-1] == '.') && p[0] == '0' && p[1] >= '0' && p[1] <= '9')
55 return 0;
56 }
57 struct in_addr address;
58 return inet_pton(AF_INET, ip, &address) == 1;
59}
60
61// Helper function to validate IPv6 address format
62// Uses POSIX inet_pton() instead of manual parsing - more robust and battle-tested
63int is_valid_ipv6(const char *ip) {
64 if (!ip) {
65 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: NULL");
66 return 0; // Invalid
67 }
68
69 size_t ip_len = strlen(ip);
70 if (ip_len == 0) {
71 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: empty string");
72 return 0; // Invalid
73 }
74
75 if (ip_len > 256) {
76 char ip_buffer[BUFFER_SIZE_SMALL];
77 SAFE_STRNCPY(ip_buffer, ip, sizeof(ip_buffer));
78 SET_ERRNO(ERROR_INVALID_PARAM, "Suspiciously long ip: %s", ip_buffer);
79 return 0; // Invalid
80 }
81
82 // Remove brackets if present (IPv6 addresses can be bracketed)
83 char normalized[INET6_ADDRSTRLEN];
84 const char *ip_to_validate = ip;
85
86 if (ip[0] == '[') {
87 // Has brackets, need to remove them
88 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
89 return 0; // Failed to parse (malformed brackets)
90 }
91 ip_to_validate = normalized;
92 }
93
94 // Use POSIX inet_pton() for robust IPv6 validation
95 // It handles all RFC 5952 compliant formats:
96 // - Full format: 2001:0db8:85a3:0000:0000:8a2e:0370:7334
97 // - Compressed: 2001:db8:85a3::8a2e:370:7334
98 // - Loopback: ::1
99 // - All zeros: ::
100 // - IPv4-mapped: ::ffff:192.0.2.1
101 struct in6_addr addr;
102 int result = inet_pton(AF_INET6, ip_to_validate, &addr);
103
104 if (result == 1) {
105 return 1; // Valid IPv6
106 } else if (result == 0) {
107 return 0; // Not a valid IPv6 address
108 } else {
109 // result < 0 means system error (e.g., unsupported address family)
110 SET_ERRNO(ERROR_INVALID_PARAM, "Failed to validate IPv6 address");
111 return 0;
112 }
113}
114
115// Parse IPv6 address, removing brackets if present
116int parse_ipv6_address(const char *input, char *output, size_t output_size) {
117 if (!input || !output || output_size == 0)
118 return -1;
119
120 size_t input_len = strlen(input);
121 if (input_len == 0)
122 return -1; // Empty string
123
124 const char *start = input;
125 const char *end = input + input_len;
126
127 // Remove brackets if present - but brackets must be matched
128 if (*start == '[') {
129 if (input_len < 2 || *(end - 1) != ']')
130 return -1; // Malformed brackets
131 start++;
132 end--;
133
134 // Check for double brackets [[...]]
135 if (start < end && *start == '[')
136 return -1; // Double opening bracket
137 } else if (*(end - 1) == ']') {
138 // Closing bracket without opening bracket
139 return -1;
140 }
141
142 size_t len = (size_t)(end - start);
143 if (len == 0)
144 return -1; // Empty content after removing brackets
145 if (len >= output_size)
146 return -1; // Buffer too small
147
148 memcpy(output, start, len);
149 output[len] = '\0';
150 return 0;
151}
152
153// Format IP address from socket address structure
154asciichat_error_t parse_numeric_socket_address(const char *host, uint16_t port, struct sockaddr_storage *address, socklen_t *length) {
155 if (!host || !*host || !address || !length)
156 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid numeric socket address");
157 struct sockaddr_in ipv4 = {.sin_family = AF_INET, .sin_port = htons(port)};
158 struct sockaddr_in6 ipv6 = {.sin6_family = AF_INET6, .sin6_port = htons(port)};
159 memset(address, 0, sizeof(*address));
160 if (inet_pton(AF_INET, host, &ipv4.sin_addr) == 1) {
161 memcpy(address, &ipv4, sizeof(ipv4));
162 *length = sizeof(ipv4);
163 return ASCIICHAT_OK;
164 }
165 if (inet_pton(AF_INET6, host, &ipv6.sin6_addr) == 1) {
166 memcpy(address, &ipv6, sizeof(ipv6));
167 *length = sizeof(ipv6);
168 return ASCIICHAT_OK;
169 }
170 *length = 0;
171 return SET_ERRNO(ERROR_INVALID_PARAM, "Expected a numeric IPv4 or IPv6 address");
172}
173
174// Format IP address with port number
175asciichat_error_t format_ip_with_port(const char *ip, uint16_t port, char *output, size_t output_size) {
176 if (!ip || !output || output_size == 0) {
177 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", ip);
178 }
179
180 if (strlen(ip) == 0) {
181 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", ip);
182 }
183
184 if (strlen(ip) > 256) {
185 char ip_buffer[BUFFER_SIZE_SMALL];
186 SAFE_STRNCPY(ip_buffer, ip, sizeof(ip_buffer));
187 return SET_ERRNO(ERROR_INVALID_PARAM, "Suspiciously long ip: %s", ip_buffer);
188 }
189
190 // Check if it's IPv6 (contains ':')
191 if (strchr(ip, ':') != NULL) {
192 // IPv6 - use bracket notation
193 size_t written = SAFE_SNPRINTF(output, output_size, "[%s]:%u", ip, port);
194 if (written >= output_size) {
195 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ip=%s or port=%u", ip, port);
196 }
197 } else {
198 // IPv4 - no brackets
199 size_t written = SAFE_SNPRINTF(output, output_size, "%s:%u", ip, port);
200 if (written >= output_size) {
201 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid ip=%s or port=%u", ip, port);
202 }
203 }
204
205 return ASCIICHAT_OK;
206}
207
208// Parse IP address and port from string
209int parse_ip_with_port(const char *input, char *ip_output, size_t ip_output_size, uint16_t *port_output) {
210 if (!input || !ip_output || !port_output || ip_output_size == 0) {
211 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", input);
212 return -1;
213 }
214
215 if (strlen(input) == 0) {
216 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IP format: %s", input);
217 return -1;
218 }
219
220 if (strlen(input) > 256) {
221 char input_buffer[BUFFER_SIZE_SMALL];
222 SAFE_STRNCPY(input_buffer, input, sizeof(input_buffer));
223 SET_ERRNO(ERROR_INVALID_PARAM, "Suspiciously long ip: %s", input_buffer);
224 return -1;
225 }
226
227 // Check for IPv6 bracket notation: [2001:db8::1]:8080
228 if (input[0] == '[') {
229 // Find closing bracket
230 const char *bracket_end = strchr(input, ']');
231 if (!bracket_end)
232 return -1; // Malformed - opening bracket but no closing bracket
233
234 // Extract IP address (without brackets)
235 size_t ip_len = (size_t)(bracket_end - input - 1);
236 if (ip_len >= ip_output_size)
237 return -1; // IP too long
238
239 memcpy(ip_output, input + 1, ip_len);
240 ip_output[ip_len] = '\0';
241
242 // Check for port after closing bracket
243 if (bracket_end[1] == ':') {
244 // Parse port using safe integer parsing
245 if (parse_port(bracket_end + 2, port_output) != ASCIICHAT_OK) {
246 return -1; // Invalid port
247 }
248 } else {
249 return -1; // Expected ':' after closing bracket
250 }
251 } else {
252 // IPv4 or hostname: "192.0.2.1:8080" or "example.com:8080"
253 // Find last ':' for port separation
254 const char *colon = strrchr(input, ':');
255 if (!colon)
256 return -1; // No port separator
257
258 // Extract IP/hostname
259 size_t ip_len = (size_t)(colon - input);
260 if (ip_len >= ip_output_size)
261 return -1; // IP too long
262
263 memcpy(ip_output, input, ip_len);
264 ip_output[ip_len] = '\0';
265
266 // Reject IPv6 without brackets (check if extracted IP contains ':')
267 // This catches cases like "::1:8080" which should be "[::1]:8080"
268 if (strchr(ip_output, ':') != NULL)
269 return -1; // IPv6 address without brackets - invalid format
270
271 // Parse port using safe integer parsing
272 if (parse_port(colon + 1, port_output) != ASCIICHAT_OK) {
273 return -1; // Invalid port
274 }
275 }
276
277 return 0;
278}
279
280// Parse address with optional port from string
281// Handles IPv4, IPv6 (with or without brackets), and hostnames
282// If no port is specified, uses default_port
283int parse_address_with_optional_port(const char *input, char *address_output, size_t address_output_size, uint16_t *port_output, uint16_t default_port) {
284 if (!input || !address_output || !port_output || address_output_size == 0) {
285 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
286 return -1;
287 }
288
289 size_t input_len = strlen(input);
290 if (input_len == 0) {
291 SET_ERRNO(ERROR_INVALID_PARAM, "Empty address string");
292 return -1;
293 }
294
295 if (input_len >= URL_BUFFER_SIZE) {
296 SET_ERRNO(ERROR_INVALID_PARAM, "Address string too long");
297 return -1;
298 }
299
300 // Case 1: Bracketed IPv6 address with or without port
301 // Examples: "[::1]" or "[::1]:8080" or "[2001:db8::1]:443"
302 if (input[0] == '[') {
303 const char *bracket_end = strchr(input, ']');
304 if (!bracket_end) {
305 SET_ERRNO(ERROR_INVALID_PARAM, "Malformed bracketed address (missing ']'): %s", input);
306 return -1;
307 }
308
309 // Extract address without brackets
310 size_t addr_len = (size_t)(bracket_end - input - 1);
311 if (addr_len == 0) {
312 SET_ERRNO(ERROR_INVALID_PARAM, "Empty bracketed address: %s", input);
313 return -1;
314 }
315 if (addr_len >= address_output_size) {
316 SET_ERRNO(ERROR_INVALID_PARAM, "Address too long for buffer");
317 return -1;
318 }
319
320 memcpy(address_output, input + 1, addr_len);
321 address_output[addr_len] = '\0';
322
323 // Validate it's a valid IPv6 address
324 if (!is_valid_ipv6(address_output)) {
325 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IPv6 address: %s", address_output);
326 return -1;
327 }
328
329 // Check for port after closing bracket
330 if (bracket_end[1] == '\0') {
331 // No port specified, use default
332 *port_output = default_port;
333 } else if (bracket_end[1] == ':') {
334 // Port specified
335 if (parse_port(bracket_end + 2, port_output) != ASCIICHAT_OK) {
336 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid port in: %s", input);
337 return -1;
338 }
339 } else {
340 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid format after ']' (expected ':' or end): %s", input);
341 return -1;
342 }
343 return 0;
344 }
345
346 // Case 2: Check if it's a valid IPv6 address without brackets (no port allowed in this case)
347 // Examples: "::1" or "2001:db8::1" or "fe80::1"
348 // Note: IPv6 addresses contain colons, so we can't use ':' as port separator without brackets
349 if (input_len < HOSTNAME_BUFFER_SIZE && is_valid_ipv6(input)) {
350 if (strlen(input) >= address_output_size) {
351 SET_ERRNO(ERROR_INVALID_PARAM, "Address too long for buffer");
352 return -1;
353 }
354 SAFE_STRNCPY(address_output, input, address_output_size);
355 *port_output = default_port;
356 return 0;
357 }
358
359 // Case 3: IPv4 or hostname, possibly with port
360 // Examples: "192.168.1.1" or "192.168.1.1:8080" or "localhost" or "example.com:443"
361 const char *last_colon = strrchr(input, ':');
362
363 if (last_colon == NULL) {
364 // No colon - just address/hostname, no port
365 // Validate and normalize before checking the ASCII output capacity.
366 char ascii[HOSTNAME_BUFFER_SIZE];
367 if (hostname_to_ascii(input, ascii, sizeof(ascii)) != ASCIICHAT_OK || strchr(ascii, '_') || ascii[strlen(ascii) - 1] == '.') {
368 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid address format: %s", input);
369 return -1;
370 }
371
372 if (strlen(ascii) >= address_output_size) {
373 SET_ERRNO(ERROR_INVALID_PARAM, "Address too long for buffer");
374 return -1;
375 }
376 SAFE_STRNCPY(address_output, ascii, address_output_size);
377 *port_output = default_port;
378 return 0;
379 }
380
381 // Has colon - extract address and port
382 size_t addr_len = (size_t)(last_colon - input);
383 if (addr_len == 0) {
384 SET_ERRNO(ERROR_INVALID_PARAM, "Empty address before port: %s", input);
385 return -1;
386 }
387 char host_input[URL_BUFFER_SIZE];
388 memcpy(host_input, input, addr_len);
389 host_input[addr_len] = '\0';
390
391 // Check if extracted address contains ':' - that would be IPv6 without brackets (invalid with port)
392 if (strchr(host_input, ':') != NULL) {
393 SET_ERRNO(ERROR_INVALID_PARAM, "IPv6 addresses must use brackets when specifying port: [%s]:%s instead of %s", host_input, last_colon + 1, input);
394 return -1;
395 }
396
397 // Validate address part is valid IPv4 or hostname
398 char ascii[HOSTNAME_BUFFER_SIZE];
399 if (hostname_to_ascii(host_input, ascii, sizeof(ascii)) != ASCIICHAT_OK || strchr(ascii, '_') || ascii[strlen(ascii) - 1] == '.') {
400 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid address format: %s", host_input);
401 return -1;
402 }
403
404 if (strlen(ascii) >= address_output_size) {
405 SET_ERRNO(ERROR_INVALID_PARAM, "Address too long for buffer");
406 return -1;
407 }
408 SAFE_STRNCPY(address_output, ascii, address_output_size);
409
410 // Parse port
411 if (parse_port(last_colon + 1, port_output) != ASCIICHAT_OK) {
412 SET_ERRNO(ERROR_INVALID_PARAM, "Invalid port in: %s", input);
413 return -1;
414 }
415
416 return 0;
417}
418
419// ============================================================================
420// IP Version Detection & Unified Validation
421// ============================================================================
422
423// Get IP address version
424int get_ip_version(const char *ip) {
425 if (!ip || strlen(ip) == 0) {
426 return 0;
427 }
428
429 // Quick heuristic: if it contains a colon, it's likely IPv6
430 // (unless it's a port separator, but we're just checking the IP part)
431 if (strchr(ip, ':') != NULL) {
432 // Could be IPv6 or bracketed IPv6
433 if (is_valid_ipv6(ip)) {
434 return 6;
435 }
436 return 0; // Has colon but not valid IPv6
437 }
438
439 // No colon, check if it's IPv4
440 if (is_valid_ipv4(ip)) {
441 return 4;
442 }
443
444 return 0; // Not valid IPv4 or IPv6
445}
446
447// Check if string is a valid IP address (IPv4 or IPv6)
448int is_valid_ip(const char *ip) {
449 if (!ip) {
450 return 0;
451 }
452
453 // Try IPv4 first (faster check)
454 if (is_valid_ipv4(ip)) {
455 return 1;
456 }
457
458 // Try IPv6
459 if (is_valid_ipv6(ip)) {
460 return 1;
461 }
462
463 return 0;
464}
465
466// ============================================================================
467// IP Address Comparison & Equality
468// ============================================================================
469
470// Compare two IP addresses for equality
471int ip_equals(const char *ip1, const char *ip2) {
472 if (!ip1 || !ip2) {
473 return 0;
474 }
475
476 // Get versions
477 int v1 = get_ip_version(ip1);
478 int v2 = get_ip_version(ip2);
479
480 // If different versions or either invalid, not equal
481 if (v1 != v2 || v1 == 0) {
482 return 0;
483 }
484
485 if (v1 == 4) {
486 // IPv4: direct string comparison after validation
487 struct in_addr addr1, addr2;
488 if (inet_pton(AF_INET, ip1, &addr1) != 1 || inet_pton(AF_INET, ip2, &addr2) != 1) {
489 return 0;
490 }
491 return addr1.s_addr == addr2.s_addr;
492 } else {
493 // IPv6: normalize then compare
494 char norm1[INET6_ADDRSTRLEN], norm2[INET6_ADDRSTRLEN];
495
496 // Remove brackets if present
497 if (parse_ipv6_address(ip1, norm1, sizeof(norm1)) != 0) {
498 return 0;
499 }
500 if (parse_ipv6_address(ip2, norm2, sizeof(norm2)) != 0) {
501 return 0;
502 }
503
504 // Parse to binary and compare
505 struct in6_addr addr1, addr2;
506 if (inet_pton(AF_INET6, norm1, &addr1) != 1 || inet_pton(AF_INET6, norm2, &addr2) != 1) {
507 return 0;
508 }
509
510 return memcmp(&addr1, &addr2, sizeof(addr1)) == 0;
511 }
512}
513
514// Compare two IP addresses for sorting
515int ip_compare(const char *ip1, const char *ip2) {
516 if (!ip1 || !ip2) {
517 return -2; // Error
518 }
519
520 int v1 = get_ip_version(ip1);
521 int v2 = get_ip_version(ip2);
522
523 // Invalid addresses sort last
524 if (v1 == 0 && v2 == 0) {
525 return 0; // Both invalid, consider equal
526 }
527 if (v1 == 0) {
528 return 1; // ip1 invalid, sorts after ip2
529 }
530 if (v2 == 0) {
531 return -1; // ip2 invalid, sorts after ip1
532 }
533
534 // IPv4 sorts before IPv6
535 if (v1 != v2) {
536 return (v1 < v2) ? -1 : 1;
537 }
538
539 if (v1 == 4) {
540 // IPv4: compare numerically
541 struct in_addr addr1, addr2;
542 if (inet_pton(AF_INET, ip1, &addr1) != 1 || inet_pton(AF_INET, ip2, &addr2) != 1) {
543 return -2; // Error
544 }
545
546 uint32_t val1 = ntohl(addr1.s_addr);
547 uint32_t val2 = ntohl(addr2.s_addr);
548
549 if (val1 < val2)
550 return -1;
551 if (val1 > val2)
552 return 1;
553 return 0;
554 } else {
555 // IPv6: compare byte by byte
556 char norm1[INET6_ADDRSTRLEN], norm2[INET6_ADDRSTRLEN];
557
558 if (parse_ipv6_address(ip1, norm1, sizeof(norm1)) != 0) {
559 return -2;
560 }
561 if (parse_ipv6_address(ip2, norm2, sizeof(norm2)) != 0) {
562 return -2;
563 }
564
565 struct in6_addr addr1, addr2;
566 if (inet_pton(AF_INET6, norm1, &addr1) != 1 || inet_pton(AF_INET6, norm2, &addr2) != 1) {
567 return -2;
568 }
569
570 return memcmp(&addr1, &addr2, sizeof(addr1));
571 }
572}
573
574// ============================================================================
575// CIDR/Subnet Utilities
576// ============================================================================
577
578// Parse CIDR notation into IP and prefix length
579int parse_cidr(const char *cidr, char *ip_out, size_t ip_out_size, int *prefix_out) {
580 if (!cidr || !ip_out || !prefix_out || ip_out_size == 0) {
581 return -1;
582 }
583
584 // Find the '/' separator
585 const char *slash = strchr(cidr, '/');
586 if (!slash) {
587 return -1; // No slash found
588 }
589
590 // Extract IP part
591 size_t ip_len = (size_t)(slash - cidr);
592 if (ip_len == 0 || ip_len >= ip_out_size) {
593 return -1;
594 }
595
596 char ip_temp[UTIL_IP_IP_TEMP_BUFFER_SIZE];
597 if (ip_len >= sizeof(ip_temp)) {
598 return -1;
599 }
600
601 memcpy(ip_temp, cidr, ip_len);
602 ip_temp[ip_len] = '\0';
603
604 // Remove brackets if IPv6
605 if (ip_temp[0] == '[') {
606 if (parse_ipv6_address(ip_temp, ip_out, ip_out_size) != 0) {
607 return -1;
608 }
609 } else {
610 if (ip_len >= ip_out_size) {
611 return -1;
612 }
613 memcpy(ip_out, ip_temp, ip_len + 1);
614 }
615
616 // Validate IP
617 int version = get_ip_version(ip_out);
618 if (version == 0) {
619 return -1; // Invalid IP
620 }
621
622 // Parse prefix length
623 const char *prefix_str = slash + 1;
624 if (strlen(prefix_str) == 0) {
625 return -1;
626 }
627
628 char *endptr;
629 long prefix = strtol(prefix_str, &endptr, 10);
630 if (*endptr != '\0' || prefix < 0) {
631 return -1; // Invalid prefix
632 }
633
634 // Validate prefix range based on IP version
635 if (version == 4 && (prefix > 32)) {
636 return -1;
637 }
638 if (version == 6 && (prefix > 128)) {
639 return -1;
640 }
641
642 *prefix_out = (int)prefix;
643 return 0;
644}
645
646// Helper: Apply netmask to IPv4 address
647static uint32_t apply_ipv4_mask(uint32_t ip, int prefix_len) {
648 if (prefix_len == 0) {
649 return 0;
650 }
651 if (prefix_len >= 32) {
652 return ip;
653 }
654 uint32_t mask = ~((1U << (32 - prefix_len)) - 1);
655 return ip & mask;
656}
657
658// Helper: Apply netmask to IPv6 address
659static void apply_ipv6_mask(struct in6_addr *addr, int prefix_len) {
660 if (prefix_len < 0 || prefix_len > 128) {
661 return;
662 }
663
664 int bytes = prefix_len / 8;
665 int bits = prefix_len % 8;
666
667 // Zero out bytes after the prefix
668 for (int i = bytes + (bits > 0 ? 1 : 0); i < 16; i++) {
669 addr->s6_addr[i] = 0;
670 }
671
672 // Mask the partial byte
673 if (bits > 0 && bytes < 16) {
674 uint8_t mask = (uint8_t)(0xFF << (8 - bits));
675 addr->s6_addr[bytes] &= mask;
676 }
677}
678
679// Check if IP is within CIDR range (parsed form)
680int ip_in_cidr_parsed(const char *ip, const char *network, int prefix_len) {
681 if (!ip || !network) {
682 return 0;
683 }
684
685 int ip_version = get_ip_version(ip);
686 int net_version = get_ip_version(network);
687
688 // Must be same version
689 if (ip_version != net_version || ip_version == 0) {
690 return 0;
691 }
692
693 if (ip_version == 4) {
694 // IPv4 comparison
695 struct in_addr ip_addr, net_addr;
696 if (inet_pton(AF_INET, ip, &ip_addr) != 1 || inet_pton(AF_INET, network, &net_addr) != 1) {
697 return 0;
698 }
699
700 uint32_t ip_val = ntohl(ip_addr.s_addr);
701 uint32_t net_val = ntohl(net_addr.s_addr);
702
703 uint32_t ip_masked = apply_ipv4_mask(ip_val, prefix_len);
704 uint32_t net_masked = apply_ipv4_mask(net_val, prefix_len);
705
706 return ip_masked == net_masked;
707 } else {
708 // IPv6 comparison
709 char ip_norm[INET6_ADDRSTRLEN], net_norm[INET6_ADDRSTRLEN];
710
711 if (parse_ipv6_address(ip, ip_norm, sizeof(ip_norm)) != 0) {
712 return 0;
713 }
714 if (parse_ipv6_address(network, net_norm, sizeof(net_norm)) != 0) {
715 return 0;
716 }
717
718 struct in6_addr ip_addr, net_addr;
719 if (inet_pton(AF_INET6, ip_norm, &ip_addr) != 1 || inet_pton(AF_INET6, net_norm, &net_addr) != 1) {
720 return 0;
721 }
722
723 // Apply mask to both addresses
724 struct in6_addr ip_masked = ip_addr;
725 struct in6_addr net_masked = net_addr;
726 apply_ipv6_mask(&ip_masked, prefix_len);
727 apply_ipv6_mask(&net_masked, prefix_len);
728
729 return memcmp(&ip_masked, &net_masked, sizeof(ip_masked)) == 0;
730 }
731}
732
733// Check if IP address is within CIDR range
734int ip_in_cidr(const char *ip, const char *cidr) {
735 if (!ip || !cidr) {
736 return 0;
737 }
738
739 char network[UTIL_IP_NETWORK_BUFFER_SIZE];
740 int prefix;
741
742 if (parse_cidr(cidr, network, sizeof(network), &prefix) != 0) {
743 return 0; // Invalid CIDR
744 }
745
746 return ip_in_cidr_parsed(ip, network, prefix);
747}
748
749// ============================================================================
750// IPv4-Mapped IPv6 Utilities
751// ============================================================================
752
753// Convert IPv4 address to IPv6-mapped format
754asciichat_error_t ipv4_to_ipv6_mapped(const char *ipv4, char *ipv6_out, size_t out_size) {
755 if (!ipv4 || !ipv6_out || out_size == 0) {
756 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
757 }
758
759 // Validate IPv4
760 if (!is_valid_ipv4(ipv4)) {
761 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IPv4 address: %s", ipv4);
762 }
763
764 // Format as ::ffff:x.x.x.x
765 size_t written = SAFE_SNPRINTF(ipv6_out, out_size, "::ffff:%s", ipv4);
766 if (written >= out_size) {
767 return SET_ERRNO(ERROR_INVALID_PARAM, "Output buffer too small");
768 }
769
770 return ASCIICHAT_OK;
771}
772
773// Check if IPv6 address is IPv4-mapped
774int is_ipv4_mapped_ipv6(const char *ipv6) {
775 if (!ipv6) {
776 return 0;
777 }
778
779 // Normalize (remove brackets)
780 char normalized[INET6_ADDRSTRLEN];
781 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
782 return 0;
783 }
784
785 // Validate IPv6
786 if (!is_valid_ipv6(normalized)) {
787 return 0;
788 }
789
790 struct in6_addr addr;
791 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
792 return 0;
793 }
794
795 // Check for ::ffff:0:0/96 prefix
796 // First 10 bytes should be 0, next 2 should be 0xff
797 for (int i = 0; i < 10; i++) {
798 if (addr.s6_addr[i] != 0) {
799 return 0;
800 }
801 }
802 if (addr.s6_addr[10] != 0xFF || addr.s6_addr[11] != 0xFF) {
803 return 0;
804 }
805
806 return 1;
807}
808
809// Extract IPv4 address from IPv6-mapped format
810asciichat_error_t extract_ipv4_from_mapped_ipv6(const char *ipv6, char *ipv4_out, size_t out_size) {
811 if (!ipv6 || !ipv4_out || out_size == 0) {
812 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
813 }
814
815 if (!is_ipv4_mapped_ipv6(ipv6)) {
816 return SET_ERRNO(ERROR_INVALID_PARAM, "Not an IPv4-mapped IPv6 address: %s", ipv6);
817 }
818
819 // Normalize
820 char normalized[INET6_ADDRSTRLEN];
821 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
822 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to parse IPv6 address");
823 }
824
825 struct in6_addr addr;
826 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
827 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to convert IPv6 address");
828 }
829
830 // Extract last 4 bytes and format as IPv4
831 struct in_addr ipv4_addr;
832 memcpy(&ipv4_addr.s_addr, &addr.s6_addr[12], 4);
833
834 if (inet_ntop(AF_INET, &ipv4_addr, ipv4_out, (socklen_t)out_size) == NULL) {
835 return SET_ERRNO(ERROR_NETWORK, "Failed to format IPv4 address");
836 }
837
838 return ASCIICHAT_OK;
839}
840
841// ============================================================================
842// IPv6 Canonicalization & Formatting
843// ============================================================================
844
845// Expand IPv6 address to full form
846asciichat_error_t expand_ipv6(const char *ipv6, char *expanded_out, size_t out_size) {
847 if (!ipv6 || !expanded_out || out_size == 0) {
848 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
849 }
850
851 // Normalize (remove brackets)
852 char normalized[INET6_ADDRSTRLEN];
853 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
854 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to parse IPv6 address");
855 }
856
857 // Validate
858 if (!is_valid_ipv6(normalized)) {
859 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IPv6 address: %s", ipv6);
860 }
861
862 struct in6_addr addr;
863 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
864 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to convert IPv6 address");
865 }
866
867 // Format as full expanded form: xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx
868 size_t written = SAFE_SNPRINTF(expanded_out, out_size, "%04x:%04x:%04x:%04x:%04x:%04x:%04x:%04x", (addr.s6_addr[0] << 8) | addr.s6_addr[1], (addr.s6_addr[2] << 8) | addr.s6_addr[3],
869 (addr.s6_addr[4] << 8) | addr.s6_addr[5], (addr.s6_addr[6] << 8) | addr.s6_addr[7], (addr.s6_addr[8] << 8) | addr.s6_addr[9],
870 (addr.s6_addr[10] << 8) | addr.s6_addr[11], (addr.s6_addr[12] << 8) | addr.s6_addr[13], (addr.s6_addr[14] << 8) | addr.s6_addr[15]);
871
872 if (written >= out_size) {
873 return SET_ERRNO(ERROR_INVALID_PARAM, "Output buffer too small");
874 }
875
876 return ASCIICHAT_OK;
877}
878
879// Canonicalize IPv6 address to standard form
880asciichat_error_t canonicalize_ipv6(const char *ipv6, char *canonical_out, size_t out_size) {
881 if (!ipv6 || !canonical_out || out_size == 0) {
882 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid arguments");
883 }
884
885 // Normalize (remove brackets)
886 char normalized[INET6_ADDRSTRLEN];
887 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
888 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to parse IPv6 address");
889 }
890
891 // Validate
892 if (!is_valid_ipv6(normalized)) {
893 return SET_ERRNO(ERROR_INVALID_PARAM, "Invalid IPv6 address: %s", ipv6);
894 }
895
896 struct in6_addr addr;
897 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
898 return SET_ERRNO(ERROR_INVALID_PARAM, "Failed to convert IPv6 address");
899 }
900
901 // Use inet_ntop which produces canonical form
902 if (inet_ntop(AF_INET6, &addr, canonical_out, (socklen_t)out_size) == NULL) {
903 return SET_ERRNO(ERROR_NETWORK, "Failed to format IPv6 address");
904 }
905
906 return ASCIICHAT_OK;
907}
908
909// Compress IPv6 address using :: notation (alias for canonicalize)
910asciichat_error_t compact_ipv6(const char *ipv6, char *compact_out, size_t out_size) {
911 return canonicalize_ipv6(ipv6, compact_out, out_size);
912}
913
914// Check if IPv6 address is anycast
915int is_anycast_ipv6(const char *ipv6) {
916 if (!ipv6) {
917 return 0;
918 }
919
920 // Normalize
921 char normalized[INET6_ADDRSTRLEN];
922 if (parse_ipv6_address(ipv6, normalized, sizeof(normalized)) != 0) {
923 return 0;
924 }
925
926 // Validate
927 if (!is_valid_ipv6(normalized)) {
928 return 0;
929 }
930
931 struct in6_addr addr;
932 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
933 return 0;
934 }
935
936 // 6to4 relay anycast: 192.88.99.0/24 (mapped to 2002:c058:6301::)
937 // Check if it matches 2002:c058:6301::
938 if (addr.s6_addr[0] == 0x20 && addr.s6_addr[1] == 0x02 && addr.s6_addr[2] == 0xc0 && addr.s6_addr[3] == 0x58 && addr.s6_addr[4] == 0x63 && addr.s6_addr[5] == 0x01) {
939 // Check if remaining bytes are zero (anycast)
940 int is_zero = 1;
941 for (int i = 6; i < 16; i++) {
942 if (addr.s6_addr[i] != 0) {
943 is_zero = 0;
944 break;
945 }
946 }
947 if (is_zero) {
948 return 1;
949 }
950 }
951
952 // Subnet-router anycast: would need subnet context to determine
953 // We can't detect this without knowing the subnet
954
955 return 0;
956}
957
958// ============================================================================
959// IP Address Classification Functions
960// ============================================================================
961
962// Extract IP address (without port) from formatted address string
963int extract_ip_from_address(const char *addr_with_port, char *ip_out, size_t ip_out_size) {
964 if (!addr_with_port || !ip_out || ip_out_size == 0) {
965 return -1;
966 }
967
968 // Check for IPv6 bracket notation: [2001:db8::1]:27224
969 if (addr_with_port[0] == '[') {
970 const char *bracket_end = strchr(addr_with_port, ']');
971 if (!bracket_end) {
972 return -1;
973 }
974 size_t ip_len = (size_t)(bracket_end - addr_with_port - 1);
975 if (ip_len >= ip_out_size) {
976 return -1;
977 }
978 memcpy(ip_out, addr_with_port + 1, ip_len);
979 ip_out[ip_len] = '\0';
980 return 0;
981 }
982
983 // IPv4: Find last colon and extract IP part
984 const char *colon = strrchr(addr_with_port, ':');
985 if (!colon) {
986 // No port, just copy the whole thing
987 SAFE_STRNCPY(ip_out, addr_with_port, ip_out_size);
988 return 0;
989 }
990
991 size_t ip_len = (size_t)(colon - addr_with_port);
992 if (ip_len >= ip_out_size) {
993 return -1;
994 }
995 memcpy(ip_out, addr_with_port, ip_len);
996 ip_out[ip_len] = '\0';
997 return 0;
998}
999
1000// Get human-readable IP type string (Localhost/LAN/Internet)
1001const char *get_ip_type_string(const char *ip) {
1002 if (!ip || ip[0] == '\0') {
1003 return "";
1004 }
1005
1006 // Check for wildcard "bind to all interfaces" addresses
1007 // IPv4: 0.0.0.0
1008 if (strcmp(ip, "0.0.0.0") == 0) {
1009 return "All Interfaces";
1010 }
1011
1012 // IPv6: :: (unspecified address)
1013 if (strcmp(ip, "::") == 0) {
1014 return "All Interfaces";
1015 }
1016
1017 // Check IPv4
1018 if (is_localhost_ipv4(ip)) {
1019 return "Localhost";
1020 }
1021 if (is_lan_ipv4(ip)) {
1022 return "LAN";
1023 }
1024 if (is_internet_ipv4(ip)) {
1025 return "Internet";
1026 }
1027
1028 // Check IPv6
1029 if (is_localhost_ipv6(ip)) {
1030 return "Localhost";
1031 }
1032 if (is_lan_ipv6(ip)) {
1033 return "LAN";
1034 }
1035 if (is_internet_ipv6(ip)) {
1036 return "Internet";
1037 }
1038
1039 return "Unknown";
1040}
1041
1042// Compare two "IP:port" strings with IPv6 normalization
1043int compare_ip_port_strings(const char *ip_port1, const char *ip_port2) {
1044 if (!ip_port1 || !ip_port2) {
1045 return 0; // Not equal
1046 }
1047
1048 // Fast path: if strings are identical, no parsing needed
1049 if (strcmp(ip_port1, ip_port2) == 0) {
1050 return 1; // Equal
1051 }
1052
1053 // Parse both IP:port strings
1055 uint16_t port1 = 0, port2 = 0;
1056
1057 if (parse_ip_with_port(ip_port1, ip1, sizeof(ip1), &port1) != 0) {
1058 return 0; // Invalid format - not equal
1059 }
1060 if (parse_ip_with_port(ip_port2, ip2, sizeof(ip2), &port2) != 0) {
1061 return 0; // Invalid format - not equal
1062 }
1063
1064 // Ports must match exactly
1065 if (port1 != port2) {
1066 return 0; // Not equal
1067 }
1068
1069 // For IPv6, normalize both addresses before comparison
1070 int version1 = get_ip_version(ip1);
1071 int version2 = get_ip_version(ip2);
1072
1073 // IP versions must match
1074 if (version1 != version2 || version1 == 0) {
1075 return 0; // Not equal
1076 }
1077
1078 if (version1 == 6) {
1079 // Normalize both IPv6 addresses
1080 char canonical1[INET6_ADDRSTRLEN], canonical2[INET6_ADDRSTRLEN];
1081 if (canonicalize_ipv6(ip1, canonical1, sizeof(canonical1)) != ASCIICHAT_OK) {
1082 return 0; // Failed to normalize - not equal
1083 }
1084 if (canonicalize_ipv6(ip2, canonical2, sizeof(canonical2)) != ASCIICHAT_OK) {
1085 return 0; // Failed to normalize - not equal
1086 }
1087 return (strcmp(canonical1, canonical2) == 0) ? 1 : 0;
1088 } else {
1089 // IPv4: use ip_equals for robust comparison
1090 return ip_equals(ip1, ip2) ? 1 : 0;
1091 }
1092}
1093
1094// Check if IPv4 address is a private/LAN address
1095int is_lan_ipv4(const char *ip) {
1096 if (!is_valid_ipv4(ip)) {
1097 return 0;
1098 }
1099
1100 struct in_addr addr;
1101 if (inet_pton(AF_INET, ip, &addr) != 1) {
1102 return 0;
1103 }
1104
1105 uint32_t ip_val = ntohl(addr.s_addr);
1106
1107 // 10.0.0.0/8: 10.0.0.0 - 10.255.255.255
1108 if ((ip_val & 0xFF000000) == 0x0A000000) {
1109 return 1;
1110 }
1111
1112 // 172.16.0.0/12: 172.16.0.0 - 172.31.255.255
1113 if ((ip_val & 0xFFF00000) == 0xAC100000) {
1114 return 1;
1115 }
1116
1117 // 192.168.0.0/16: 192.168.0.0 - 192.168.255.255
1118 if ((ip_val & 0xFFFF0000) == 0xC0A80000) {
1119 return 1;
1120 }
1121
1122 return 0;
1123}
1124
1125// Check if IPv6 address is a private/LAN address (ULA)
1126int is_lan_ipv6(const char *ip) {
1127 if (!ip) {
1128 return 0;
1129 }
1130
1131 // Remove brackets if present
1132 char normalized[INET6_ADDRSTRLEN];
1133 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1134 return 0;
1135 }
1136
1137 // Validate the normalized address
1138 if (!is_valid_ipv6(normalized)) {
1139 return 0;
1140 }
1141
1142 struct in6_addr addr;
1143 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1144 return 0;
1145 }
1146
1147 // fc00::/7: Unique Local Addresses (ULA)
1148 // First byte should be 0xfc or 0xfd
1149 if ((addr.s6_addr[0] & 0xFE) == 0xFC) {
1150 return 1;
1151 }
1152
1153 return 0;
1154}
1155
1156// Check if IPv4 address is a broadcast address
1157int is_broadcast_ipv4(const char *ip) {
1158 if (!is_valid_ipv4(ip)) {
1159 return 0;
1160 }
1161
1162 struct in_addr addr;
1163 if (inet_pton(AF_INET, ip, &addr) != 1) {
1164 return 0;
1165 }
1166
1167 uint32_t ip_val = ntohl(addr.s_addr);
1168
1169 // Limited broadcast: 255.255.255.255
1170 if (ip_val == 0xFFFFFFFF) {
1171 return 1;
1172 }
1173
1174 return 0;
1175}
1176
1177// Check if IPv6 address is a multicast address
1178int is_broadcast_ipv6(const char *ip) {
1179 if (!ip) {
1180 return 0;
1181 }
1182
1183 // Remove brackets if present
1184 char normalized[INET6_ADDRSTRLEN];
1185 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1186 return 0;
1187 }
1188
1189 // Validate the normalized address
1190 if (!is_valid_ipv6(normalized)) {
1191 return 0;
1192 }
1193
1194 struct in6_addr addr;
1195 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1196 return 0;
1197 }
1198
1199 // ff00::/8: Multicast addresses
1200 // First byte should be 0xff
1201 if (addr.s6_addr[0] == 0xFF) {
1202 return 1;
1203 }
1204
1205 return 0;
1206}
1207
1208// Check if IPv4 address is localhost
1209int is_localhost_ipv4(const char *ip) {
1210 if (!is_valid_ipv4(ip)) {
1211 return 0;
1212 }
1213
1214 struct in_addr addr;
1215 if (inet_pton(AF_INET, ip, &addr) != 1) {
1216 return 0;
1217 }
1218
1219 uint32_t ip_val = ntohl(addr.s_addr);
1220
1221 // 127.0.0.0/8: Loopback addresses
1222 if ((ip_val & 0xFF000000) == 0x7F000000) {
1223 return 1;
1224 }
1225
1226 return 0;
1227}
1228
1229// Check if IPv6 address is localhost
1230int is_localhost_ipv6(const char *ip) {
1231 if (!ip) {
1232 return 0;
1233 }
1234
1235 // Remove brackets if present
1236 char normalized[INET6_ADDRSTRLEN];
1237 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1238 return 0;
1239 }
1240
1241 // Validate the normalized address
1242 if (!is_valid_ipv6(normalized)) {
1243 return 0;
1244 }
1245
1246 struct in6_addr addr;
1247 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1248 return 0;
1249 }
1250
1251 // ::1: Loopback address
1252 // All bytes should be 0 except the last byte which should be 1
1253 for (int i = 0; i < 15; i++) {
1254 if (addr.s6_addr[i] != 0) {
1255 return 0;
1256 }
1257 }
1258 if (addr.s6_addr[15] != 1) {
1259 return 0;
1260 }
1261
1262 return 1;
1263}
1264
1265// Check if IPv4 address is a link-local address
1266int is_link_local_ipv4(const char *ip) {
1267 if (!is_valid_ipv4(ip)) {
1268 return 0;
1269 }
1270
1271 struct in_addr addr;
1272 if (inet_pton(AF_INET, ip, &addr) != 1) {
1273 return 0;
1274 }
1275
1276 uint32_t ip_val = ntohl(addr.s_addr);
1277
1278 // 169.254.0.0/16: Link-local addresses (APIPA)
1279 if ((ip_val & 0xFFFF0000) == 0xA9FE0000) {
1280 return 1;
1281 }
1282
1283 return 0;
1284}
1285
1286// Check if IPv6 address is a link-local address
1287int is_link_local_ipv6(const char *ip) {
1288 if (!ip) {
1289 return 0;
1290 }
1291
1292 // Remove brackets if present
1293 char normalized[INET6_ADDRSTRLEN];
1294 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1295 return 0;
1296 }
1297
1298 // Validate the normalized address
1299 if (!is_valid_ipv6(normalized)) {
1300 return 0;
1301 }
1302
1303 struct in6_addr addr;
1304 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1305 return 0;
1306 }
1307
1308 // fe80::/10: Link-local addresses
1309 // First byte should be 0xfe, second byte & 0xc0 should be 0x80
1310 if (addr.s6_addr[0] == 0xFE && (addr.s6_addr[1] & 0xC0) == 0x80) {
1311 return 1;
1312 }
1313
1314 return 0;
1315}
1316
1317// Check if IPv4 address is a public internet address
1318int is_internet_ipv4(const char *ip) {
1319 if (!is_valid_ipv4(ip)) {
1320 return 0;
1321 }
1322
1323 struct in_addr addr;
1324 if (inet_pton(AF_INET, ip, &addr) != 1) {
1325 return 0;
1326 }
1327
1328 uint32_t ip_val = ntohl(addr.s_addr);
1329
1330 // Exclude private/LAN addresses
1331 if (is_lan_ipv4(ip)) {
1332 return 0;
1333 }
1334
1335 // Exclude loopback
1336 if (is_localhost_ipv4(ip)) {
1337 return 0;
1338 }
1339
1340 // Exclude link-local
1341 if (is_link_local_ipv4(ip)) {
1342 return 0;
1343 }
1344
1345 // Exclude broadcast
1346 if (is_broadcast_ipv4(ip)) {
1347 return 0;
1348 }
1349
1350 // Exclude multicast: 224.0.0.0/4
1351 if ((ip_val & 0xF0000000) == 0xE0000000) {
1352 return 0;
1353 }
1354
1355 // Exclude 0.0.0.0/8: "This network"
1356 if ((ip_val & 0xFF000000) == 0x00000000) {
1357 return 0;
1358 }
1359
1360 // Exclude 100.64.0.0/10: Shared Address Space (RFC 6598)
1361 if ((ip_val & 0xFFC00000) == 0x64400000) {
1362 return 0;
1363 }
1364
1365 // Exclude 192.0.0.0/24: IETF Protocol Assignments
1366 if ((ip_val & 0xFFFFFF00) == 0xC0000000) {
1367 return 0;
1368 }
1369
1370 // Exclude 192.0.2.0/24: TEST-NET-1
1371 if ((ip_val & 0xFFFFFF00) == 0xC0000200) {
1372 return 0;
1373 }
1374
1375 // Exclude 198.18.0.0/15: Benchmarking
1376 if ((ip_val & 0xFFFE0000) == 0xC6120000) {
1377 return 0;
1378 }
1379
1380 // Exclude 198.51.100.0/24: TEST-NET-2
1381 if ((ip_val & 0xFFFFFF00) == 0xC6336400) {
1382 return 0;
1383 }
1384
1385 // Exclude 203.0.113.0/24: TEST-NET-3
1386 if ((ip_val & 0xFFFFFF00) == 0xCB007100) {
1387 return 0;
1388 }
1389
1390 // Exclude 240.0.0.0/4: Reserved for future use
1391 if ((ip_val & 0xF0000000) == 0xF0000000) {
1392 return 0;
1393 }
1394
1395 // If none of the exclusions matched, it's a public internet address
1396 return 1;
1397}
1398
1399// Check if IPv6 address is a public internet address
1400int is_internet_ipv6(const char *ip) {
1401 if (!ip) {
1402 return 0;
1403 }
1404
1405 // Remove brackets if present
1406 char normalized[INET6_ADDRSTRLEN];
1407 if (parse_ipv6_address(ip, normalized, sizeof(normalized)) != 0) {
1408 return 0;
1409 }
1410
1411 // Validate the normalized address
1412 if (!is_valid_ipv6(normalized)) {
1413 return 0;
1414 }
1415
1416 struct in6_addr addr;
1417 if (inet_pton(AF_INET6, normalized, &addr) != 1) {
1418 return 0;
1419 }
1420
1421 // Exclude loopback
1422 if (is_localhost_ipv6(ip)) {
1423 return 0;
1424 }
1425
1426 // Exclude link-local
1427 if (is_link_local_ipv6(ip)) {
1428 return 0;
1429 }
1430
1431 // Exclude ULA
1432 if (is_lan_ipv6(ip)) {
1433 return 0;
1434 }
1435
1436 // Exclude multicast
1437 if (is_broadcast_ipv6(ip)) {
1438 return 0;
1439 }
1440
1441 // Exclude unspecified address: ::
1442 int is_unspecified = 1;
1443 for (int i = 0; i < 16; i++) {
1444 if (addr.s6_addr[i] != 0) {
1445 is_unspecified = 0;
1446 break;
1447 }
1448 }
1449 if (is_unspecified) {
1450 return 0;
1451 }
1452
1453 // Exclude IPv4-mapped IPv6: ::ffff:0:0/96
1454 if (addr.s6_addr[0] == 0 && addr.s6_addr[1] == 0 && addr.s6_addr[2] == 0 && addr.s6_addr[3] == 0 && addr.s6_addr[4] == 0 && addr.s6_addr[5] == 0 && addr.s6_addr[6] == 0 && addr.s6_addr[7] == 0 &&
1455 addr.s6_addr[8] == 0 && addr.s6_addr[9] == 0 && addr.s6_addr[10] == 0xFF && addr.s6_addr[11] == 0xFF) {
1456 return 0;
1457 }
1458
1459 // Exclude IPv4-compatible IPv6: ::/96 (deprecated)
1460 if (addr.s6_addr[0] == 0 && addr.s6_addr[1] == 0 && addr.s6_addr[2] == 0 && addr.s6_addr[3] == 0 && addr.s6_addr[4] == 0 && addr.s6_addr[5] == 0 && addr.s6_addr[6] == 0 && addr.s6_addr[7] == 0 &&
1461 addr.s6_addr[8] == 0 && addr.s6_addr[9] == 0 && addr.s6_addr[10] == 0 && addr.s6_addr[11] == 0) {
1462 // But not ::, which we already excluded above
1463 if (addr.s6_addr[12] != 0 || addr.s6_addr[13] != 0 || addr.s6_addr[14] != 0 || addr.s6_addr[15] != 0) {
1464 return 0;
1465 }
1466 }
1467
1468 // Exclude documentation prefix: 2001:db8::/32
1469 if (addr.s6_addr[0] == 0x20 && addr.s6_addr[1] == 0x01 && addr.s6_addr[2] == 0x0D && addr.s6_addr[3] == 0xB8) {
1470 return 0;
1471 }
1472
1473 // Exclude 6to4: 2002::/16
1474 if (addr.s6_addr[0] == 0x20 && addr.s6_addr[1] == 0x02) {
1475 return 0;
1476 }
1477
1478 // If none of the exclusions matched, it's likely a global unicast address
1479 // Global unicast is typically 2000::/3, but let's accept anything that's not excluded
1480 return 1;
1481}
#define SET_ERRNO(code,...)
Common buffer size definitions.
Application limits and constraints.
#define BUFFER_SIZE_SMALL
Small buffer size (256 bytes).
unsigned short uint16_t
unsigned int uint32_t
#define SAFE_STRNCPY(dst, src, size)
#define SAFE_SNPRINTF(buffer, buffer_size,...)
unsigned char uint8_t
asciichat_error_t
Error and exit codes - unified status values (0-255).
Definition error_codes.h:48
@ ERROR_NETWORK
Definition error_codes.h:76
@ ASCIICHAT_OK
Definition error_codes.h:50
@ ERROR_INVALID_PARAM
#define URL_BUFFER_SIZE
#define HOSTNAME_BUFFER_SIZE
#define IP_ADDRESS_BUFFER_SIZE
int ip_compare(const char *ip1, const char *ip2)
Compare two IP addresses for sorting.
Definition ip.c:515
asciichat_error_t expand_ipv6(const char *ipv6, char *expanded_out, size_t out_size)
Expand IPv6 address to full form.
Definition ip.c:846
int is_lan_ipv6(const char *ip)
Check if IPv6 address is a private/LAN address.
Definition ip.c:1126
asciichat_error_t format_ip_with_port(const char *ip, uint16_t port, char *output, size_t output_size)
Format IP address with port number.
Definition ip.c:175
int is_broadcast_ipv6(const char *ip)
Check if IPv6 address is a multicast address.
Definition ip.c:1178
int ip_in_cidr(const char *ip, const char *cidr)
Check if IP address is within CIDR range.
Definition ip.c:734
int is_link_local_ipv6(const char *ip)
Check if IPv6 address is a link-local address.
Definition ip.c:1287
asciichat_error_t extract_ipv4_from_mapped_ipv6(const char *ipv6, char *ipv4_out, size_t out_size)
Extract IPv4 address from IPv6-mapped format.
Definition ip.c:810
int is_localhost_ipv6(const char *ip)
Check if IPv6 address is localhost.
Definition ip.c:1230
int is_internet_ipv4(const char *ip)
Check if IPv4 address is a public internet address.
Definition ip.c:1318
int is_valid_ipv4(const char *ip)
Check if a string is a valid IPv4 address.
Definition ip.c:32
int extract_ip_from_address(const char *addr_with_port, char *ip_out, size_t ip_out_size)
Extract IP address (without port) from formatted address string.
Definition ip.c:963
const char * get_ip_type_string(const char *ip)
Get human-readable string describing IP address type.
Definition ip.c:1001
int parse_ip_with_port(const char *input, char *ip_output, size_t ip_output_size, uint16_t *port_output)
Parse IP address and port from string.
Definition ip.c:209
int is_lan_ipv4(const char *ip)
Check if IPv4 address is a private/LAN address.
Definition ip.c:1095
asciichat_error_t compact_ipv6(const char *ipv6, char *compact_out, size_t out_size)
Compress IPv6 address using :: notation.
Definition ip.c:910
int parse_cidr(const char *cidr, char *ip_out, size_t ip_out_size, int *prefix_out)
Parse CIDR notation into IP and prefix length.
Definition ip.c:579
int is_valid_ipv6(const char *ip)
Check if a string is a valid IPv6 address.
Definition ip.c:63
int is_ipv4_mapped_ipv6(const char *ipv6)
Check if IPv6 address is IPv4-mapped.
Definition ip.c:774
int is_broadcast_ipv4(const char *ip)
Check if IPv4 address is a broadcast address.
Definition ip.c:1157
int is_localhost_ipv4(const char *ip)
Check if IPv4 address is localhost.
Definition ip.c:1209
int ip_equals(const char *ip1, const char *ip2)
Compare two IP addresses for equality.
Definition ip.c:471
int parse_address_with_optional_port(const char *input, char *address_output, size_t address_output_size, uint16_t *port_output, uint16_t default_port)
Parse address with optional port from string.
Definition ip.c:283
int is_link_local_ipv4(const char *ip)
Check if IPv4 address is a link-local address.
Definition ip.c:1266
int is_valid_ip(const char *ip)
Check if string is a valid IP address (IPv4 or IPv6).
Definition ip.c:448
int is_internet_ipv6(const char *ip)
Check if IPv6 address is a public internet address.
Definition ip.c:1400
int ip_in_cidr_parsed(const char *ip, const char *network, int prefix_len)
Check if IP is within CIDR range (parsed form).
Definition ip.c:680
asciichat_error_t canonicalize_ipv6(const char *ipv6, char *canonical_out, size_t out_size)
Canonicalize IPv6 address to standard form.
Definition ip.c:880
int get_ip_version(const char *ip)
Get IP address version.
Definition ip.c:424
int parse_ipv6_address(const char *input, char *output, size_t output_size)
Parse IPv6 address, removing brackets if present.
Definition ip.c:116
int compare_ip_port_strings(const char *ip_port1, const char *ip_port2)
Compare two "IP:port" strings with IPv6 normalization.
Definition ip.c:1043
int is_anycast_ipv6(const char *ipv6)
Check if IPv6 address is anycast.
Definition ip.c:915
asciichat_error_t ipv4_to_ipv6_mapped(const char *ipv4, char *ipv6_out, size_t out_size)
Convert IPv4 address to IPv6-mapped format.
Definition ip.c:754
asciichat_error_t hostname_to_ascii(const char *hostname, char *output, size_t capacity)
Definition url.c:103
⚙️ Common definitions, error codes, macros, and types shared throughout the application
#define UTIL_IP_NETWORK_BUFFER_SIZE
Definition ip.c:9
#define UTIL_IP_IP2_BUFFER_SIZE
Definition ip.c:10
asciichat_error_t parse_numeric_socket_address(const char *host, uint16_t port, struct sockaddr_storage *address, socklen_t *length)
Definition ip.c:154
#define UTIL_IP_IP_TEMP_BUFFER_SIZE
Definition ip.c:8
🌍 IP Address Parsing and Formatting Utilities
📝 Logging API with multiple log levels and terminal output control
🔤 String Manipulation and Shell Escaping Utilities
🌐 Production-Grade URL Validation and Parsing
asciichat_error_t parse_port(const char *str, uint16_t *out_port)
Parse port number (1-65535) from string.
🔍 Safe Parsing Utilities