-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathip_address.h
More file actions
1425 lines (1177 loc) · 49.2 KB
/
ip_address.h
File metadata and controls
1425 lines (1177 loc) · 49.2 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* ip-sockets-cpp-lite — header-only C++ networking utilities
* https://github.com/biaks/ip-sockets-cpp-lite
*
* Copyright (c) 2021 Yan Kryukov ianiskr@gmail.com
* Licensed under the MIT License
*/
#pragma once
// ORDERS BEGIN
#include <type_traits>
#include <cstdint>
#if defined(_MSC_VER)
#include <stdlib.h>
#define COMMON_LITTLE_ENDIAN 1
#define bswap_16(x) _byteswap_ushort(x)
#define bswap_32(x) _byteswap_ulong(x)
#define bswap_64(x) _byteswap_uint64(x)
#elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)
#define COMMON_LITTLE_ENDIAN 1
#include <byteswap.h>
//#define bswap_16(x) __builtin_bswap16(x)
//#define bswap_32(x) __builtin_bswap32(x)
//#define bswap_64(x) __builtin_bswap64(x)
#elif defined(__BYTE_ORDER__) && (__BYTE_ORDER__ == __ORDER_BIG_ENDIAN__)
#define COMMON_LITTLE_ENDIAN 0
#include <byteswap.h>
//#define bswap_16(x) __builtin_bswap16(x)
//#define bswap_32(x) __builtin_bswap32(x)
//#define bswap_64(x) __builtin_bswap64(x)
#else
#error "Unsupported platform endian detection"
#endif
namespace orders {
// network -> host
template <typename T> inline std::enable_if_t<sizeof(T) == 1, T> ntohT (const T& value) { return value; }
template <typename T> inline std::enable_if_t<sizeof(T) == 2, T> ntohT (const T& value) { return (COMMON_LITTLE_ENDIAN) ? bswap_16(value) : value; }
template <typename T> inline std::enable_if_t<sizeof(T) == 4, T> ntohT (const T& value) { return (COMMON_LITTLE_ENDIAN) ? bswap_32(value) : value; }
template <typename T> inline std::enable_if_t<sizeof(T) == 8, T> ntohT (const T& value) { return (COMMON_LITTLE_ENDIAN) ? bswap_64(value) : value; }
// host -> network
template <typename T> inline std::enable_if_t<sizeof(T) == 1, T> htonT (const T& value) { return value; }
template <typename T> inline std::enable_if_t<sizeof(T) == 2, T> htonT (const T& value) { return (COMMON_LITTLE_ENDIAN) ? bswap_16(value) : value; }
template <typename T> inline std::enable_if_t<sizeof(T) == 4, T> htonT (const T& value) { return (COMMON_LITTLE_ENDIAN) ? bswap_32(value) : value; }
template <typename T> inline std::enable_if_t<sizeof(T) == 8, T> htonT (const T& value) { return (COMMON_LITTLE_ENDIAN) ? bswap_64(value) : value; }
} // namespace common
// ORDERS END
#include <array>
#include <iostream>
#include <string>
#include <cassert>
#include <algorithm> // std::copy_n
#include <functional> // std::hash
// base classes for working with ipv4 and ipv6 addresses classes are based on standard std::array<uint, type>
// and can be "overlayed" onto corresponding memory areas, for example:
// uint8_t fragment[10] = {0xff, 0xc0, 0xa8, 0x02, 0x01, 0xff,0xff,0xff,0xff,0xff};
// ip4_t& ipv4 = *((ip4_t*)&fragment[1]);
// after that, all tools for working with this ip address become available, without copying the ip address itself
//
// also, classes can be declared in two different ways:
// use ip4_t and ip6_t classes directly where it is known in advance which ip address type will be used
// or use the generic form ip_t<type> where working with an abstract ip address is intended, for example:
// template <ip_type_e type>
// struct ip_address_holder_t {
// ip_t<type> ip_address;
// };
//
// also, this universal form allows reverse type deduction and determining, for example, the ip address type:
// template <ip_type_e type>
// struct ip_detector;
// template <>
// ip_detector<ip_t<v4>> {
// static inline const char* type() { return "ipv4"; }
// }
// ip_detector<ip_t<v6>> {
// static inline const char* type() { return "ipv6"; }
// }
// template <class Ip>
// void print_type () { std::cout << ip_detector<Ip>::type(); }
namespace ipsockets {
struct ip4_t : public std::array<uint8_t, 4> {
/// @brief Parses a text string with an IP address according to the rules.
/// The string can contain from one to four numbers separated by dots.
/// Each number can be encoded as HEX (hexadecimal number) or as DEC (decimal number).
/// If there is one number, it is interpreted as uint32 (i.e., one number contains the entire ip address).
/// If there are 2 to 4 numbers, they are interpreted as values of individual address octets, empty octets are filled with zeros.
/// The IP address value is stored in the std::array<uint8_t, 4> array from high byte to low byte (big endian).
/// If parsing fails, the result will be 0.0.0.0. To get confirmation of successful parsing, pass a pointer to a bool variable
/// as the success parameter, which will be set to true in case of successful parsing.
/// @param value - pointer to the string with the ip address, it can be null-terminated or not, in the second case, the length parameter should be set correctly.
/// @param length - length of the string with the ip address, if the string is null-terminated, then this parameter can be left as default.
/// @param success - optional parameter for confirming successful parsing.
/// @return reference to the current object with the parsed ip address, in case of parsing failure, the result will be 0.0.0.0
/// @details Possibly examples:
/// "192.168.2.1"
/// "192.0xa8.2.0x1"
/// "0xc0a80201"
/// "3232236033"
/// "127.1"
ip4_t& from_str (const char* value, size_t length = 20, bool* success = nullptr) {
enum { start, cont, hex, dec, error } state = start;
uint8_t result[3] = {};
size_t octet = 0;
uint32_t accum = 0;
while (length-- && *value != '\0' && state != error) {
if (state == start) {
if (*value < '0' || '9' < *value)
state = error;
else if (*value == '0' && length >= 2 && (*(value + 1) == 'x' || *(value + 1) == 'X')) {
value += 2;
length -= 2;
state = hex;
}
else
state = dec;
}
if (state == dec) {
if ('0' <= *value && *value <= '9')
accum = accum * 10 + (*value - '0');
else if (*value == '.')
state = cont;
else
state = error;
}
else if (state == hex) {
if ('0' <= *value && *value <= '9') accum = (accum << 4) + ( *value - '0');
else if ('a' <= *value && *value <= 'f') accum = (accum << 4) + (10 + *value - 'a');
else if ('A' <= *value && *value <= 'F') accum = (accum << 4) + (10 + *value - 'A');
else if (*value == '.')
state = cont;
else
state = error;
}
if (state == cont) {
if (accum > 0xff || octet >= 3)
state = error;
else {
result[octet++] = (uint8_t)accum;
accum = 0;
state = start;
}
}
value++;
}
if (state == error || state == start) {
*this = ip4_t {};
if (success)
*success = false;
return *this;
}
else if (octet != 0) {
if (accum > 0xff)
*this = ip4_t {};
else {
// 1.2.3.4 1.2.x.3 1.x.x.2 1.x.x.x
// 0 1 2 3 0 1 x 2 0 x x 1 0 x x x
for (size_t i = 0; i < octet; i++)
(*this)[i] = result[i];
for (size_t i = octet; i < 3; i++)
(*this)[i] = 0;
(*this)[3] = (uint8_t)accum;
}
}
else
*((uint32_t*)this) = orders::htonT (accum);
if (success)
*success = true;
return *this;
}
/// @brief Parses a text string with an IP address according to the rules.
/// The string can contain from one to four numbers separated by dots.
/// Each number can be encoded as HEX (hexadecimal number) or as DEC (decimal number).
/// If there is one number, it is interpreted as uint32 (i.e., one number contains the entire ip address).
/// If there are 2 to 4 numbers, they are interpreted as values of individual address octets, empty octets are filled with zeros.
/// The IP address value is stored in the std::array<uint8_t, 4> array from high byte to low byte (big endian).
/// If parsing fails, the result will be 0.0.0.0. To get confirmation of successful parsing, pass a pointer to a bool variable
/// as the success parameter, which will be set to true in case of successful parsing.
/// @param value - std::string with the ip address
/// @param success - optional parameter for confirming successful parsing.
/// @return reference to the current object with the parsed ip address, in case of parsing failure, the result will be 0.0.0.0
/// @details Possibly examples:
/// "192.168.2.1"
/// "192.0xa8.2.0x1"
/// "0xc0a80201"
/// "3232236033"
/// "127.1"
ip4_t& from_str (const std::string& value, bool* success = nullptr) {
return from_str (value.data (), value.size (), success);
}
ip4_t () = default;
ip4_t (std::array<uint8_t, 4>&& arr) : std::array<uint8_t, 4> (arr) {}
template <size_t Size>
ip4_t (char (&&value)[Size]) {
from_str (value, Size);
}
ip4_t (const char* value) {
from_str (value);
}
ip4_t (const char* value, size_t length) {
from_str (value, length);
}
ip4_t (const std::string& value) {
from_str (value.data (), value.size ());
}
ip4_t (const uint32_t& value) {
*((uint32_t*)this) = orders::htonT (value);
}
ip4_t (uint32_t&& value) {
*((uint32_t*)this) = orders::htonT (value);
}
ip4_t (uint8_t&& v1, uint8_t&& v2, uint8_t&& v3, uint8_t&& v4) {
(*this)[0] = v1; (*this)[1] = v2; (*this)[2] = v3; (*this)[3] = v4;
}
ip4_t (uint8_t prefix) {
const uint8_t masks[9] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
const uint8_t byte_size = 8;
for (size_t i = 0; i < 4; ++i) {
if (prefix >= byte_size) {
this->operator[] (i) = masks[byte_size];
prefix -= byte_size;
}
else {
this->operator[] (i) = masks[prefix];
prefix = 0;
}
}
}
ip4_t& set_mask (uint8_t prefix) {
ip4_t mask (prefix);
this->operator&= (mask);
return *this;
}
ip4_t operator& (const ip4_t& other) {
ip4_t result;
*((uint32_t*)&result) = *((uint32_t*)this) & *((uint32_t*)&other);
return result;
}
void operator&= (const ip4_t& other) {
*((uint32_t*)this) &= *((uint32_t*)&other);
}
void rotate () {
std::swap ((*this)[0], (*this)[3]);
std::swap ((*this)[1], (*this)[2]);
}
/// @brief Converts ipv4 address to text representation.
/// @return text representation of ipv4 address
std::string to_str () const {
return std::to_string ((*this)[0]) + '.' + std::to_string ((*this)[1]) + '.' + std::to_string ((*this)[2]) + '.' + std::to_string ((*this)[3]);
}
operator std::string () const {
return to_str ();
}
operator uint32_t () const {
return orders::ntohT (*((uint32_t*)this));
}
};
static inline std::ostream& operator<< (std::ostream& os, const ip4_t& ipv4) {
os << ipv4.to_str ();
return os;
}
} // namespace ipsockets
template<>
struct std::hash<ipsockets::ip4_t> {
inline std::size_t operator() (const ipsockets::ip4_t& ip) const {
return (uint32_t)ip;
}
};
namespace ipsockets {
struct ip6_t : public std::array<uint8_t, 16> {
/// @brief Parses a text string with an IP address according to the rules.
/// The string can contain from zero to eight HEX (hexadecimal) numbers separated by ':'.
/// Additionally, compression of one or more zero numbers using '::' is supported
/// Also, notation with an ipv4 address instead of the last two numbers is supported. The ipv4 address can only be written with decimal digits.
/// If parsing fails, the result will be '::'. To get confirmation of successful parsing, pass a pointer to a bool variable
/// as the success parameter, which will be set to true in case of successful parsing.
/// @param value - pointer to the string with the ip address, it can be null-terminated or not, in the second case, the length parameter should be set correctly.
/// @param length - length of the string with the ip address, if the string is null-terminated, then this parameter can be left as default.
/// @param success - optional parameter for confirming successful parsing.
/// @return reference to the current object with the parsed ip address, in case of parsing failure, the result will be '::'
/// @details Possibly examples:
/// "5555:6666:7777:8888:9999:aaaa:bbbb:cccc"
/// "1:2:3:4:5:6:7:8"
/// "1::5:6:7:8"
/// "::5:6:7:8"
/// "1:2:3:4::"
/// "::"
/// "1:2:3:4:5:6:192.168.2.1"
/// "::192.168.2.1"
/// "127.0.0.1" -> "::ffff:127.0.0.1"
/// "5555:6666:7777:8888:9999:aaaa:255.255.255.255"
ip6_t& from_str (const char* value, size_t length = 45, bool* success = nullptr) {
enum { start, proc, error } state = start;
uint16_t result_hex[8] = {};
uint8_t result_dec[3] = {};
size_t index_hex = 0;
size_t index_dec = 0;
size_t separator = SIZE_MAX;
uint32_t accum_dec = 0;
uint32_t accum_hex = 0;
uint8_t sym = 0;
while (length-- && *value != '\0' && state != error) {
// ::xx.. ..xx::xx.. ..xx:: ::
if (length >= 1 && *value == ':' && *(value + 1) == ':') {
if (separator == SIZE_MAX && index_dec == 0 && accum_hex <= 0xffff && index_hex < 7) {
if (state == proc) {
result_hex[index_hex++] = (uint16_t)accum_hex;
accum_hex = 0;
accum_dec = 0;
}
separator = index_hex;
value += 1;
length -= 1;
}
else
state = error;
}
// ..xx:xx..
else if (*value == ':') {
if (state == proc && index_dec == 0 && accum_hex <= 0xffff && index_hex < 7) {
result_hex[index_hex++] = (uint16_t)accum_hex;
accum_hex = 0;
accum_dec = 0;
}
else
state = error;
}
// ..xx:n.n.n.n ..xx::n.n.n.n ::n.n.n.n
else if (*value == '.') {
if (state == proc && accum_dec <= 0xff && index_dec <= 6 && index_dec < 3) {
result_dec[index_dec++] = (uint8_t)accum_dec;
accum_dec = 0;
accum_hex = 0;
}
else
state = error;
}
// xxxx
else {
if ('0' <= *value && *value <= '9') sym = *value - '0';
else if ('a' <= *value && *value <= 'f') sym = 10 + *value - 'a';
else if ('A' <= *value && *value <= 'F') sym = 10 + *value - 'A';
else
state = error;
accum_hex = (accum_hex << 4) + sym;
accum_dec = accum_dec * 10 + sym;
if (state != error)
state = proc;
}
value++;
}
if ((state == start && separator == SIZE_MAX) || (index_dec != 0 && index_dec != 3) || (index_dec == 0 && accum_hex > 0xffff) || (index_dec == 3 && accum_dec > 0xff))
state = error;
if (state == error) {
*this = {};
if (success)
*success = false;
return *this;
}
if (index_dec == 3) { // found an ipv4 address in the end, then the last two numbers of ipv6 will be formed from this ipv4 address
if (index_hex == 0) // if there is nothing at front of ipv4 address, then the ipv4 address should be written as ipv4 over ipv6 ::ffff:x.x.x.x
result_hex[index_hex++] = 0xffff;
result_hex[index_hex++] = (result_dec[0] << 8) | result_dec[1];
result_hex[index_hex++] = (result_dec[2] << 8) | (uint8_t)accum_dec;
}
else
result_hex[index_hex++] = (uint16_t)accum_hex;
size_t current = 0;
if (separator == SIZE_MAX)
separator = 0;
// copy all numbers before separator (if separator is 0, then this loop will be skipped)
for (; current < separator; current++)
((uint16_t*)this)[current] = orders::htonT (result_hex[current]);
// fill zeros in place of separator
for (; current < separator + (8 - index_hex); current++)
((uint16_t*)this)[current] = 0x0000;
// copy all numbers after separator
for (; current < 8; current++)
((uint16_t*)this)[current] = orders::htonT (result_hex[current - (8 - index_hex)]);
if (success)
*success = true;
return *this;
}
/// @brief Parses a text string with an IP address according to the rules.
/// The string can contain from zero to eight HEX (hexadecimal) numbers separated by ':'.
/// Additionally, compression of one or more zero numbers using '::' is supported
/// Also, notation with an ipv4 address instead of the last two numbers is supported. The ipv4 address can only be written with decimal digits.
/// If parsing fails, the result will be '::'. To get confirmation of successful parsing, pass a pointer to a bool variable
/// as the success parameter, which will be set to true in case of successful parsing.
/// @param value - string with the ip address.
/// @param success - optional parameter for confirming successful parsing.
/// @return reference to the current object with the parsed ip address, in case of parsing failure, the result will be '::'
/// @details Possibly examples:
/// "5555:6666:7777:8888:9999:aaaa:bbbb:cccc"
/// "1:2:3:4:5:6:7:8"
/// "1::5:6:7:8"
/// "::5:6:7:8"
/// "1:2:3:4::"
/// "::"
/// "1:2:3:4:5:6:192.168.2.1"
/// "::192.168.2.1"
/// "127.0.0.1" -> "::ffff:127.0.0.1"
/// "5555:6666:7777:8888:9999:aaaa:255.255.255.255"
ip6_t& from_str (const std::string& value, bool* success = nullptr) {
return from_str (value.data (), value.size (), success);
}
ip6_t () = default;
ip6_t (std::array<uint8_t, 16>&& arr) : std::array<uint8_t, 16> (arr) {}
// For translating ipv4 addresses to ipv6, we choose the method supported by ClickHouse ::ffff:x.x.x.x/96 rfc4291 https://www.iana.org/go/rfc4291
ip6_t (std::array<uint8_t, 4>&& ipv4) : std::array<uint8_t, 16> () {
(*this)[10] = 0xff; (*this)[11] = 0xff; (*this)[12] = ipv4[0]; (*this)[13] = ipv4[1]; (*this)[14] = ipv4[2]; (*this)[15] = ipv4[3];
}
// For translating ipv4 addresses to ipv6, we choose the method supported by ClickHouse ::ffff:x.x.x.x/96 rfc4291 https://www.iana.org/go/rfc4291
ip6_t (const ip4_t& ipv4) : std::array<uint8_t, 16> () {
(*this)[10] = 0xff; (*this)[11] = 0xff; (*this)[12] = ipv4[0]; (*this)[13] = ipv4[1]; (*this)[14] = ipv4[2]; (*this)[15] = ipv4[3];
}
template <size_t Size>
ip6_t (char (&&value)[Size]) {
from_str (value, Size);
}
ip6_t (const char* value) {
from_str (value);
}
ip6_t (const char* value, size_t length) {
from_str (value, length);
}
ip6_t (const std::string& value) {
from_str (value.data (), value.size ());
}
ip6_t (uint8_t&& v1, uint8_t&& v2, uint8_t&& v3, uint8_t&& v4, uint8_t&& v5, uint8_t&& v6, uint8_t&& v7, uint8_t&& v8,
uint8_t&& v9, uint8_t&& v10, uint8_t&& v11, uint8_t&& v12, uint8_t&& v13, uint8_t&& v14, uint8_t&& v15, uint8_t&& v16) {
((uint8_t*)this)[0] = orders::htonT (v1); ((uint8_t*)this)[1] = orders::htonT (v2);
((uint8_t*)this)[2] = orders::htonT (v3); ((uint8_t*)this)[3] = orders::htonT (v4);
((uint8_t*)this)[4] = orders::htonT (v5); ((uint8_t*)this)[5] = orders::htonT (v6);
((uint8_t*)this)[6] = orders::htonT (v7); ((uint8_t*)this)[7] = orders::htonT (v8);
((uint8_t*)this)[8] = orders::htonT (v9); ((uint8_t*)this)[9] = orders::htonT (v10);
((uint8_t*)this)[10] = orders::htonT (v11); ((uint8_t*)this)[11] = orders::htonT (v12);
((uint8_t*)this)[12] = orders::htonT (v13); ((uint8_t*)this)[13] = orders::htonT (v14);
((uint8_t*)this)[14] = orders::htonT (v15); ((uint8_t*)this)[15] = orders::htonT (v16);
}
ip6_t (uint16_t&& v1, uint16_t&& v2, uint16_t&& v3, uint16_t&& v4, uint16_t&& v5, uint16_t&& v6, uint16_t&& v7, uint16_t&& v8) {
((uint16_t*)this)[0] = orders::htonT (v1); ((uint16_t*)this)[1] = orders::htonT (v2);
((uint16_t*)this)[2] = orders::htonT (v3); ((uint16_t*)this)[3] = orders::htonT (v4);
((uint16_t*)this)[4] = orders::htonT (v5); ((uint16_t*)this)[5] = orders::htonT (v6);
((uint16_t*)this)[6] = orders::htonT (v7); ((uint16_t*)this)[7] = orders::htonT (v8);
}
const ip4_t& get_ip4 () const {
return *((ip4_t*)this + 3); // 4*3 = 12
}
ip4_t& get_ip4 () {
return *((ip4_t*)this + 3); // 4*3 = 12
}
bool is_ip4() const {
uint32_t first = ((const uint32_t*)this)[0];
uint32_t second = ((uint32_t*)this)[1];
uint32_t thrird = ((uint32_t*)this)[2];
return first == 0 &&
second == 0 &&
thrird == 0xffff0000;
}
ip6_t (uint8_t prefix) {
const uint8_t masks[9] = { 0x00, 0x80, 0xc0, 0xe0, 0xf0, 0xf8, 0xfc, 0xfe, 0xff };
const uint8_t byte_size = 8;
for (size_t i = 0; i < 16; ++i) {
if (prefix >= byte_size) {
this->operator[] (i) = masks[byte_size];
prefix -= byte_size;
} else {
this->operator[] (i) = masks[prefix];
prefix = 0;
}
}
}
ip6_t& set_mask (uint8_t prefix) {
ip6_t mask (prefix);
this->operator&= (mask);
return *this;
}
/// @brief Converts ipv6 address to text representation.
/// Supports optional address compression and optional output of the last two groups as an IPv4 address,
/// always outputting the special case of ip4-over-ip6 as '::ffff:x.x.x.x' string.
/// @param reduction - enable address compression (replacing empty groups with '::')
/// @param embedded_ipv4 - enable force representation of last two groups as ipv4 address
/// @return text representation of ipv6 address
std::string to_str (bool reduction = true, bool embedded_ipv4 = false) const {
std::string result;
const char symbols[] = "0123456789abcdef";
bool dot = false;
const uint16_t* part = (uint16_t*)this;
enum { start, found, end } zero = (reduction) ? start : end;
result.reserve (45); // maximum length "xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:nnn.nnn.nnn.nnn" = 45
for (size_t i = 0; i < 8; i++, part++) {
if (*part == 0 && zero == start) {
zero = found;
result.push_back (':');
if (dot == false) result.push_back (':');
}
else
if (*part != 0 && zero == found)
zero = end;
if (zero != found) {
bool non_zero = false;
uint8_t half_of_byte;
half_of_byte = *((uint8_t*)part ) >> 4; if (half_of_byte) non_zero = true; if (non_zero) result.push_back (symbols[half_of_byte]);
half_of_byte = *((uint8_t*)part ) & 15; if (half_of_byte) non_zero = true; if (non_zero) result.push_back (symbols[half_of_byte]);
half_of_byte = *((uint8_t*)part + 1) >> 4; if (half_of_byte) non_zero = true; if (non_zero) result.push_back (symbols[half_of_byte]);
half_of_byte = *((uint8_t*)part + 1) & 15; result.push_back (symbols[half_of_byte]);
dot = true;
if (i != 7)
result.push_back (':');
}
if ((i == 4 && zero == found && *(part + 1) == 0xffff) || (embedded_ipv4 && i == 5)) {
if (i == 4) {
for (size_t i = 0; i < 4; i++)
result.push_back('f');
result.push_back(':');
part += 2;
}
else
part += 1;
for (size_t i = 0; i < 4; i++) {
uint8_t byte = *((uint8_t*)part + i); // byte = XYZ
uint8_t div = byte % 100; // div = XYZ % 100 = 0YZ
bool non_zero = false;
byte /= 100; // byte = XYZ / 100 = X
if (byte != 0) {
result.push_back (symbols[byte]);
non_zero = true;
}
byte = div / 10; // byte = 0YZ / 10 = Y
div = div % 10; // div = 0YZ % 10 = Z
if (byte != 0 || non_zero == true)
result.push_back (symbols[byte]);
result.push_back (symbols[div]);
if (i != 3)
result.push_back ('.');
}
break;
}
}
return result;
}
operator std::string () const {
return to_str ();
}
operator bool () const {
const uint64_t* part1 = (uint64_t*)this;
const uint64_t* part2 = part1 + 1;
return (*part1 || *part2);
}
ip6_t operator& (const ip6_t& other_ip) {
ip6_t result;
*((uint64_t*)&result) = *((uint64_t*)this) & *((uint64_t*)&other_ip);
*((uint64_t*)&result + 1) = *((uint64_t*)this + 1) & *((uint64_t*)&other_ip + 1);
return result;
}
void operator&= (const ip6_t& other_ip) {
*((uint64_t*)this) &= *((uint64_t*)&other_ip);
*((uint64_t*)this + 1) &= *((uint64_t*)&other_ip + 1);
}
};
static inline std::ostream& operator<< (std::ostream& os, const ip6_t& ipv6) {
os << ipv6.to_str ();
return os;
}
} // namespace ipsockets
template <>
struct std::hash<ipsockets::ip6_t> {
inline std::size_t operator() (const ipsockets::ip6_t& ip) const noexcept{
return *((uint64_t*)&ip) ^ *((uint64_t*)&ip + 1);
}
};
namespace ipsockets {
enum ip_type_e { v4 = 4, v6 = 16 };
template <ip_type_e type>
struct ip_t_;
template <>
struct ip_t_<v4> {
using type = ip4_t;
};
template <>
struct ip_t_<v6> {
using type = ip6_t;
};
template <ip_type_e type>
using ip_t = typename ip_t_<type>::type;
// addr_t
struct addr4_t {
ip4_t ip = {};
uint16_t port = 0; // le
// nnn.nnn.nnn.nnn:ppppp
// any_format_supported_by_ip4_t_class:ppppp
addr4_t& from_str (const char* value, size_t length = 21, bool* success = nullptr) {
size_t ip_length = 0;
const char* ptr = value;
size_t accum = 0;
while (*ptr && length--) {
if (ip_length == 0) {
if (*ptr == ':')
ip_length = ptr - value;
else if ((*ptr < '0' || '9' < *ptr) && (*ptr < 'a' || 'f' < *ptr) && (*ptr < 'A' || 'F' < *ptr) && *ptr != 'x' && *ptr != '.')
break; // this is error, break
}
else {
if ('0' <= *ptr && *ptr <= '9')
accum = accum * 10 + (*ptr - '0');
else
break;
}
ptr++;
}
ip.from_str (value, ip_length, success);
if (ip_length == 0 || accum == 0 || accum > 0xffff) {
if (success)
*success = false;
*this = {};
}
else
port = (uint16_t)accum;
return *this;
}
addr4_t () = default;
addr4_t (const ip4_t& ip_, uint16_t port_) : ip (ip_), port (port_) {}
template <size_t Size>
addr4_t (char (&&value)[Size]) {
from_str (value, Size);
}
addr4_t (const char* value) {
from_str (value);
}
addr4_t (const char* value, size_t length) {
from_str (value, length);
}
addr4_t (const std::string& value) {
from_str (value.data (), value.size ());
}
template <size_t Size>
addr4_t (const std::array<uint8_t, Size>& value) {
from_str (value.data(), Size);
}
std::string to_str () const {
return ip.to_str() + ':' + std::to_string (port);
}
operator std::string () const {
return to_str ();
}
operator bool () const {
return (ip && port != 0);
}
bool operator== (const addr4_t& other_addr) const {
return this->ip == other_addr.ip && this->port == other_addr.port;
}
};
static inline std::ostream& operator<< (std::ostream& os, const addr4_t& addr4) {
os << addr4.to_str ();
return os;
}
} // namespace ipsockets
template <>
struct std::hash<ipsockets::addr4_t> {
std::size_t operator() (const ipsockets::addr4_t& addr4) const noexcept {
return std::hash<ipsockets::ip4_t> {}(addr4.ip) ^ std::hash<uint16_t> {}(addr4.port);
}
};
namespace ipsockets {
struct addr6_t {
ip6_t ip;
uint16_t port; // le
// [xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:nnn.nnn.nnn.nnn]:ppppp
// [any_format_supported_by_ip6_t_class]:ppppp
addr6_t& from_str (const char* value, size_t length = 53, bool* success = nullptr) {
enum { open, ipp, close, tochki, portt, error, end } state = open;
const char* ip_ptr = nullptr;
size_t ip_length = 0;
const char* ptr = value;
size_t accum = 0;
while (*ptr && length-- && state != error) {
switch (state) {
case open:
if (*ptr == '[') {
ip_ptr = ptr + 1;
state = ipp;
}
else
state = error;
break;
case ipp:
if (*ptr == ']') {
ip_length = ptr - ip_ptr;
if (ip_length >= 2)
state = close;
else
state = error;
}
else if ((*ptr < '0' || '9' < *ptr) && (*ptr < 'a' || 'f' < *ptr) && (*ptr < 'A' || 'F' < *ptr) && *ptr != ':' && *ptr != '.')
state = error;
break;
case close:
if (*ptr == ':')
state = portt;
else
state = error;
break;
case portt:
if ('0' <= *ptr && *ptr <= '9')
accum = accum * 10 + (*ptr - '0');
else if (accum != 0)
state = end;
else
state = error;
break;
default:
break;
}
ptr++;
}
if (state != error)
ip.from_str (ip_ptr, ip_length, success);
if (state == error || accum > 0xffff) {
if (success)
*success = false;
*this = {};
}
else
port = (uint16_t)accum;
return *this;
}
addr6_t () = default;
addr6_t (const ip6_t& ip_, uint16_t port_) : ip (ip_), port (port_) {}
template <size_t Size>
addr6_t (char (&&value)[Size]) {
from_str (value, Size);
}
addr6_t (const char* value) {
from_str (value);
}
addr6_t (const char* value, size_t length) {
from_str (value, length);
}
addr6_t (const std::string& value) {
from_str (value.data (), value.size ());
}
template <size_t Size>
addr6_t (const std::array<uint8_t, Size>& value) {
from_str (value.data (), Size);
}
std::string to_str (bool reduction = true, bool embedded_ipv4 = false) const {
return std::string ("[") + ip.to_str (reduction, embedded_ipv4) + std::string ("]:") + std::to_string (port);
}
operator std::string () const {
return to_str ();
}
operator bool () const {
return (ip && port != 0);
}
bool operator== (const addr6_t& other_addr) const {
return this->ip == other_addr.ip && this->port == other_addr.port;
}
};
static inline std::ostream& operator<< (std::ostream& os, const addr6_t& addr6) {
os << addr6.to_str ();
return os;
}
} // namespace ipsockets
template <>
struct std::hash<ipsockets::addr6_t> {
inline std::size_t operator() (const ipsockets::addr6_t& addr6) const noexcept {
return std::hash<ipsockets::ip6_t> {}(addr6.ip) ^ std::hash<uint16_t> {}(addr6.port);
}
};
namespace ipsockets {
template <ip_type_e type>
struct addr_t_;
template <>
struct addr_t_<v4> {
using type = addr4_t;
};
template <>
struct addr_t_<v6> {
using type = addr6_t;
};
template <ip_type_e type>
using addr_t = typename addr_t_<type>::type;
// ============================================================
// ip_prefix_raw_t — variable-length prefix overlay (C-style)
// ============================================================
/// @brief Raw variable-length IP prefix for zero-copy overlay on packed binary data.
/// Layout: [1 byte length_in_bits] [ceil(length/8) bytes of prefix value]
/// @note Uses flexible array member (compiler extension supported by GCC, Clang, MSVC).
/// Do NOT create instances on the stack — use reinterpret_cast on a sufficiently large buffer.
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable: 4200) // nonstandard extension: zero-sized array
#endif
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#endif
struct ip_prefix_raw_t {
uint8_t length; ///< Prefix length in bits (0..128)
uint8_t bytes[]; ///< Prefix value bytes (actual size = value_size())
/// @brief Returns the number of bytes needed to store 'length' bits.
uint8_t value_size () const {
return (uint8_t)((length >> 3) + ((length & 0x7) ? 1 : 0));
}
/// @brief Returns the total size of this prefix in bytes (1 byte for length + value bytes).
uint8_t size () const {
return (uint8_t)(1 + value_size ());
}
/// @brief Returns the value of a specific bit in the prefix (MSB-first order within each byte).
/// @param index - Bit index (0-based, must be < length).
bool get_bit (uint8_t index) const {
assert (index < length);
return (bytes[index >> 3] >> (7 - (index & 0x7))) & 0x1;
}
};
#if defined(__GNUC__) || defined(__clang__)
#pragma GCC diagnostic pop
#endif
#if defined(_MSC_VER)
#pragma warning(pop)
#endif
// ============================================================
// prefix4_t / prefix6_t / prefix_t<> — IP prefix (ip + length)
// ============================================================