-
Notifications
You must be signed in to change notification settings - Fork 9
/
ipaddr.go
2864 lines (2578 loc) · 119 KB
/
ipaddr.go
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
//
// Copyright 2020-2022 Sean C Foley
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package ipaddr
import (
"fmt"
"github.com/seancfoley/ipaddress-go/ipaddr/addrerr"
"github.com/seancfoley/ipaddress-go/ipaddr/addrstr"
"math/big"
"net"
"net/netip"
"strings"
"unsafe"
)
const (
PrefixLenSeparator = '/'
PrefixLenSeparatorStr = "/"
)
// IPVersion is the version type used by IP address types.
type IPVersion string
const (
// IndeterminateIPVersion represents an unspecified IP address version
IndeterminateIPVersion IPVersion = ""
// IPv4 represents Internet Protocol version 4
IPv4 IPVersion = "IPv4"
// IPv6 represents Internet Protocol version 6
IPv6 IPVersion = "IPv6"
)
// IsIPv6 returns true if this represents version 6
func (version IPVersion) IsIPv6() bool {
return len(version) == 4 && strings.EqualFold(string(version), string(IPv6))
}
// IsIPv4 returns true if this represents version 4
func (version IPVersion) IsIPv4() bool {
return len(version) == 4 && strings.EqualFold(string(version), string(IPv4))
}
// IsIndeterminate returns true if this represents an unspecified IP address version
func (version IPVersion) IsIndeterminate() bool {
if len(version) == 4 {
// we allow mixed case in the event code is converted a string to IPVersion
dig := version[3]
if dig != '4' && dig != '6' {
return true
}
dig = version[0]
if dig != 'I' && dig != 'i' {
return true
}
dig = version[1]
if dig != 'P' && dig != 'p' {
return true
}
dig = version[2]
if dig != 'v' && dig != 'V' {
return true
}
return false
}
return true
}
// index returns an index starting from 0 with IndeterminateIPVersion being the highest
func (version IPVersion) index() int {
if version.IsIPv4() {
return 0
} else if version.IsIPv6() {
return 1
}
return 2
}
// Equal returns whether the given version matches this version. Two indeterminate versions always match, even if their associated strings do not.
func (version IPVersion) Equal(other IPVersion) bool {
return strings.EqualFold(string(version), string(other)) || (version.IsIndeterminate() && other.IsIndeterminate())
}
// String returns "IPv4", "IPv6", or the zero-value "" representing an indeterminate version
func (version IPVersion) String() string {
return string(version)
}
func (version IPVersion) GetNetwork() (network IPAddressNetwork) {
if version.IsIPv6() {
network = ipv6Network
} else if version.IsIPv4() {
network = ipv4Network
}
return
}
func (version IPVersion) toType() (t addrType) {
if version.IsIPv6() {
t = ipv6Type
} else if version.IsIPv4() {
t = ipv4Type
}
return
}
// GetMaxSegmentValue returns the maximum possible segment value for this IP version, determined by the number of bits per segment.
func (version IPVersion) GetMaxSegmentValue() SegInt {
if version.IsIPv4() {
return IPv4MaxValuePerSegment
} else if version.IsIPv6() {
return IPv6MaxValuePerSegment
}
return 0
}
// GetBytesPerSegment returns the number of bytes comprising each segment in this address or subnet. Segments in the same address are equal length.
func (version IPVersion) GetBytesPerSegment() int {
if version.IsIPv4() {
return IPv4BytesPerSegment
} else if version.IsIPv6() {
return IPv6BytesPerSegment
}
return 0
}
// GetBitsPerSegment returns the number of bits comprising each segment for this address version, either 8 or 16 for IPv4 and IPv6 respectively. Segments in the same address are equal length.
func (version IPVersion) GetBitsPerSegment() BitCount {
if version.IsIPv4() {
return IPv4BitsPerSegment
} else if version.IsIPv6() {
return IPv6BitsPerSegment
}
return 0
}
// GetByteCount returns the number of bytes comprising an address of this IP Version.
func (version IPVersion) GetByteCount() int {
if version.IsIPv4() {
return IPv4ByteCount
} else if version.IsIPv6() {
return IPv6ByteCount
}
return 0
}
// GetSegmentCount returns the number of segments comprising an address of this IP Version: 4 for IPv4 and 8 for IPv6.
func (version IPVersion) GetSegmentCount() int {
if version.IsIPv4() {
return IPv4SegmentCount
} else if version.IsIPv6() {
return IPv6SegmentCount
}
return 0
}
// GetBitCount returns the number of bits comprising an address of this IP Version.
func (version IPVersion) GetBitCount() BitCount {
if version.IsIPv4() {
return IPv4BitCount
} else if version.IsIPv6() {
return IPv6BitCount
}
return 0
}
func createIPAddress(section *AddressSection, zone Zone) *IPAddress {
return &IPAddress{
ipAddressInternal{
addressInternal{
section: section,
zone: zone,
cache: &addressCache{},
},
},
}
}
func newIPAddressZoned(section *IPAddressSection, zone Zone) *IPAddress {
result := createIPAddress(section.ToSectionBase(), zone)
if zone != NoZone { // will need to cache its own strings
result.cache.stringCache = &stringCache{}
}
return result
}
// necessary to avoid direct access to IPAddress
type ipAddressInternal struct {
addressInternal
}
func (addr *ipAddressInternal) toIPAddress() *IPAddress {
return (*IPAddress)(unsafe.Pointer(addr))
}
func (addr *ipAddressInternal) getIPVersion() IPVersion {
if addr.isIPv4() {
return IPv4
} else if addr.isIPv6() {
return IPv6
}
return IndeterminateIPVersion
}
func (addr *ipAddressInternal) getNetworkPrefixLen() PrefixLen {
section := addr.section
if section == nil {
return nil
}
return section.ToIP().getNetworkPrefixLen()
}
// GetNetworkPrefixLen returns the prefix length, or nil if there is no prefix length.
// GetNetworkPrefixLen is equivalent to the method GetPrefixLen.
func (addr *ipAddressInternal) GetNetworkPrefixLen() PrefixLen {
return addr.getNetworkPrefixLen().copy()
}
func (addr *ipAddressInternal) getNetNetIPAddr() netip.Addr {
netAddr, _ := netip.AddrFromSlice(addr.getBytes())
return netAddr
}
func (addr *ipAddressInternal) getUpperNetNetIPAddr() netip.Addr {
netAddr, _ := netip.AddrFromSlice(addr.getUpperBytes())
return netAddr
}
// IncludesZeroHost returns whether the subnet contains an individual address with a host of zero. If the subnet has no prefix length it returns false.
// If the prefix length matches the bit count, then it returns true.
//
// Otherwise, it checks whether it contains an individual address for which all bits past the prefix are zero.
func (addr *ipAddressInternal) IncludesZeroHost() bool {
section := addr.section
if section == nil {
return false
}
return section.ToIP().IncludesZeroHost()
}
func (addr *ipAddressInternal) includesZeroHostLen(networkPrefixLength BitCount) bool {
return addr.getSection().IncludesZeroHostLen(networkPrefixLength)
}
// IncludesMaxHost returns whether the subnet contains an individual address with a host of all one-bits. If the subnet has no prefix length it returns false.
// If the prefix length matches the bit count, then it returns true.
//
// Otherwise, it checks whether it contains an individual address for which all bits past the prefix are one.
func (addr *ipAddressInternal) IncludesMaxHost() bool {
section := addr.section
if section == nil {
return false
}
return section.ToIP().IncludesMaxHost()
}
func (addr *ipAddressInternal) includesMaxHostLen(networkPrefixLength BitCount) bool {
return addr.getSection().IncludesMaxHostLen(networkPrefixLength)
}
// IsSingleNetwork returns whether the network section of the address, the prefix, consists of a single value.
//
// If it has no prefix length, it returns true if not multiple, if it contains only a single individual address.
func (addr *ipAddressInternal) IsSingleNetwork() bool {
section := addr.section
return section == nil || section.ToIP().IsSingleNetwork()
}
// IsMaxHost returns whether this section has a prefix length and if so,
// whether the host section is always all one-bits, the max value, for all individual addresses in this subnet.
//
// If the host section is zero length (there are zero host bits), IsMaxHost returns true.
func (addr *ipAddressInternal) IsMaxHost() bool {
section := addr.section
return section != nil && section.ToIP().IsMaxHost()
}
// IsMaxHostLen returns whether the host section is always one-bits, the max value, for all individual addresses in this subnet,
// for the given prefix length.
//
// If the host section is zero length (there are zero host bits), IsMaxHostLen returns true.
func (addr *ipAddressInternal) isMaxHostLen(prefLen BitCount) bool {
return addr.getSection().IsMaxHostLen(prefLen)
}
// IsZeroHost returns whether this subnet has a prefix length and if so,
// whether the host section is always zero for all individual addresses in this subnet.
//
// If the host section is zero length (there are zero host bits), IsZeroHost returns true.
func (addr *ipAddressInternal) IsZeroHost() bool {
section := addr.section
return section != nil && section.ToIP().IsZeroHost()
}
// IsZeroHostLen returns whether the host section is always zero for all individual sections in this address section,
// for the given prefix length.
//
// If the host section is zero length (there are zero host bits), IsZeroHostLen returns true.
func (addr *ipAddressInternal) isZeroHostLen(prefLen BitCount) bool {
return addr.getSection().IsZeroHostLen(prefLen)
}
// when boundariesOnly is true, there will be no error
func (addr *ipAddressInternal) toZeroHost(boundariesOnly bool) (res *IPAddress, err addrerr.IncompatibleAddressError) {
section, err := addr.section.toIPAddressSection().toZeroHost(boundariesOnly)
if err == nil {
res = addr.checkIdentity(section)
}
return
}
func (addr *ipAddressInternal) toZeroHostLen(prefixLength BitCount) (res *IPAddress, err addrerr.IncompatibleAddressError) {
section, err := addr.getSection().toZeroHostLen(prefixLength)
if err == nil {
res = addr.checkIdentity(section)
}
return
}
func (addr *ipAddressInternal) toZeroNetwork() *IPAddress {
return addr.checkIdentity(addr.getSection().toZeroNetwork())
}
func (addr *ipAddressInternal) toMaxHost() (res *IPAddress, err addrerr.IncompatibleAddressError) {
section, err := addr.section.toIPAddressSection().toMaxHost()
if err == nil {
res = addr.checkIdentity(section)
}
return
}
func (addr *ipAddressInternal) toMaxHostLen(prefixLength BitCount) (res *IPAddress, err addrerr.IncompatibleAddressError) {
section, err := addr.getSection().toMaxHostLen(prefixLength)
if err == nil {
res = addr.checkIdentity(section)
}
return
}
func (addr *ipAddressInternal) checkIdentity(section *IPAddressSection) *IPAddress {
if section == nil {
return nil
}
sect := section.ToSectionBase()
if sect == addr.section {
return addr.toIPAddress()
}
return createIPAddress(sect, addr.zone)
}
func (addr *ipAddressInternal) getSection() *IPAddressSection {
return addr.section.ToIP()
}
func (addr *ipAddressInternal) adjustPrefixLen(prefixLen BitCount) *IPAddress {
return addr.checkIdentity(addr.getSection().adjustPrefixLen(prefixLen))
}
func (addr *ipAddressInternal) adjustPrefixLenZeroed(prefixLen BitCount) (res *IPAddress, err addrerr.IncompatibleAddressError) {
section, err := addr.getSection().adjustPrefixLenZeroed(prefixLen)
if err == nil {
res = addr.checkIdentity(section)
}
return
}
// GetBlockMaskPrefixLen returns the prefix length if this address is equivalent to the mask for a CIDR prefix block.
// Otherwise, it returns nil.
// A CIDR network mask is an address with all ones in the network section and then all zeros in the host section.
// A CIDR host mask is an address with all zeros in the network section and then all ones in the host section.
// The prefix length is the bit-length of the network section.
//
// Also, keep in mind that the prefix length returned by this method is not equivalent to the prefix length of this instance,
// indicating the network and host section of this address.
// The prefix length returned here indicates the whether the value of this address can be used as a mask for the network and host
// section of any other address. Therefore, the two values can be different values, or one can be nil while the other is not.
//
// This method applies only to the lower value of the range if this address represents multiple values.
func (addr *ipAddressInternal) GetBlockMaskPrefixLen(network bool) PrefixLen {
section := addr.section
if section == nil {
return nil
}
return section.ToIP().GetBlockMaskPrefixLen(network)
}
func (addr *ipAddressInternal) spanWithPrefixBlocks() []ExtendedIPSegmentSeries {
wrapped := addr.toIPAddress().Wrap()
if addr.IsSequential() {
if addr.IsSinglePrefixBlock() {
return []ExtendedIPSegmentSeries{wrapped}
}
return getSpanningPrefixBlocks(wrapped, wrapped)
}
return spanWithPrefixBlocks(wrapped)
}
func (addr *ipAddressInternal) spanWithSequentialBlocks() []ExtendedIPSegmentSeries {
wrapped := addr.toIPAddress().Wrap()
if addr.IsSequential() {
return []ExtendedIPSegmentSeries{wrapped}
}
return spanWithSequentialBlocks(wrapped)
}
func (addr *ipAddressInternal) coverSeriesWithPrefixBlock() ExtendedIPSegmentSeries {
// call from wrapper
if addr.IsSinglePrefixBlock() {
return addr.toIPAddress().Wrap()
}
return coverWithPrefixBlock(
addr.getLower().ToIP().Wrap(),
addr.getUpper().ToIP().Wrap(),
)
}
func (addr *ipAddressInternal) coverWithPrefixBlock() *IPAddress {
// call from ip ipv4 ipv6
if addr.IsSinglePrefixBlock() {
return addr.toIPAddress()
}
res := coverWithPrefixBlock(
addr.getLower().ToIP().Wrap(),
addr.getUpper().ToIP().Wrap(),
)
return res.(WrappedIPAddress).IPAddress
}
func (addr *ipAddressInternal) coverWithPrefixBlockTo(other *IPAddress) *IPAddress {
res := getCoveringPrefixBlock(
addr.toIPAddress().Wrap(),
other.Wrap(),
)
return res.(WrappedIPAddress).IPAddress
}
func (addr *ipAddressInternal) getNetworkMask(network IPAddressNetwork) *IPAddress {
var prefLen BitCount
if addr.isPrefixed() {
prefLen = addr.getNetworkPrefixLen().bitCount()
} else {
prefLen = addr.GetBitCount()
}
return network.GetNetworkMask(prefLen)
}
func (addr *ipAddressInternal) getHostMask(network IPAddressNetwork) *IPAddress {
var prefLen BitCount
if addr.isPrefixed() {
prefLen = addr.getNetworkPrefixLen().bitCount()
}
return network.GetHostMask(prefLen)
}
func (addr *ipAddressInternal) toCanonicalWildcardString() string {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.ToIPv6().toCanonicalWildcardStringZoned(addr.zone)
}
return cacheStr(&cache.canonicalWildcardString,
func() string {
return addr.section.ToIPv6().toCanonicalWildcardStringZoned(addr.zone)
})
}
return addr.getSection().ToCanonicalWildcardString()
}
func (addr *ipAddressInternal) toNormalizedWildcardString() string {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.ToIPv6().toNormalizedWildcardStringZoned(addr.zone)
}
return cacheStr(&cache.normalizedWildcardString,
func() string {
return addr.section.ToIPv6().toNormalizedWildcardStringZoned(addr.zone)
})
}
return addr.getSection().ToNormalizedWildcardString()
}
func (addr *ipAddressInternal) toSegmentedBinaryString() string {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.ToIPv6().toSegmentedBinaryStringZoned(addr.zone)
}
return cacheStr(&cache.segmentedBinaryString,
func() string {
return addr.section.ToIPv6().toSegmentedBinaryStringZoned(addr.zone)
})
}
return addr.getSection().ToSegmentedBinaryString()
}
func (addr *ipAddressInternal) toSQLWildcardString() string {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.ToIPv6().toSQLWildcardStringZoned(addr.zone)
}
return cacheStr(&cache.sqlWildcardString,
func() string {
return addr.section.ToIPv6().toSQLWildcardStringZoned(addr.zone)
})
}
return addr.getSection().ToSQLWildcardString()
}
func (addr *ipAddressInternal) toFullString() string {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.ToIPv6().toFullStringZoned(addr.zone)
}
return cacheStr(&cache.fullString,
func() string {
return addr.section.ToIPv6().toFullStringZoned(addr.zone)
})
}
return addr.getSection().ToFullString()
}
func (addr *ipAddressInternal) toReverseDNSString() (string, addrerr.IncompatibleAddressError) {
return addr.getSection().ToReverseDNSString()
}
func (addr *ipAddressInternal) toPrefixLenString() string {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.ToIPv6().toPrefixLenStringZoned(addr.zone)
}
return cacheStr(&cache.networkPrefixLengthString,
func() string {
return addr.section.ToIPv6().toPrefixLenStringZoned(addr.zone)
})
}
return addr.getSection().ToPrefixLenString()
}
func (addr *ipAddressInternal) toSubnetString() string {
if addr.hasZone() {
return addr.toPrefixLenString()
}
return addr.getSection().ToSubnetString()
}
func (addr *ipAddressInternal) toCompressedWildcardString() string {
if addr.hasZone() {
cache := addr.getStringCache()
if cache == nil {
return addr.section.ToIPv6().toCompressedWildcardStringZoned(addr.zone)
}
return cacheStr(&cache.compressedWildcardString,
func() string {
return addr.section.ToIPv6().toCompressedWildcardStringZoned(addr.zone)
})
}
return addr.getSection().ToCompressedWildcardString()
}
func (addr *ipAddressInternal) getNetwork() IPAddressNetwork {
return addr.getSection().getNetwork()
}
//// only needed for godoc / pkgsite
// GetPrefixCount returns the count of prefixes in this address or subnet.
//
// The prefix length is given by GetPrefixLen.
//
// If this has a non-nil prefix length, returns the count of the range of values in the prefix.
//
// If this has a nil prefix length, returns the same value as GetCount.
func (addr *ipAddressInternal) GetPrefixCount() *big.Int {
return addr.addressInternal.GetPrefixCount()
}
// GetPrefixCountLen returns the count of prefixes in this address or subnet for the given prefix length.
//
// If not a subnet of multiple addresses, or a subnet with just single prefix of the given length, returns 1.
func (addr *ipAddressInternal) GetPrefixCountLen(prefixLen BitCount) *big.Int {
return addr.addressInternal.GetPrefixCountLen(prefixLen)
}
// GetBlockCount returns the count of distinct values in the given number of initial (more significant) segments.
func (addr *ipAddressInternal) GetBlockCount(segments int) *big.Int {
return addr.addressInternal.GetBlockCount(segments)
}
// GetPrefixLen returns the prefix length, or nil if there is no prefix length.
//
// A prefix length indicates the number of bits in the initial part of the address that comprise the prefix.
//
// A prefix is a part of the address that is not specific to that address but common amongst a group of addresses, such as a CIDR prefix block subnet.
//
// For IP addresses, the prefix is explicitly defined when the address is created. For example, "1.2.0.0/16" has a prefix length of 16, while "1.2.*.*" has no prefix length,
// even though they both represent the same set of addresses and are considered equal. Prefixes can be considered variable for a given IP address and can depend on routing.
//
// The methods GetMinPrefixLenForBlock and GetPrefixLenForSingleBlock can help you to obtain or define a prefix length if one does not exist already.
// The method ToPrefixBlockLen allows you to create the subnet consisting of the block of addresses for any given prefix length.
func (addr *ipAddressInternal) GetPrefixLen() PrefixLen {
return addr.addressInternal.GetPrefixLen()
}
// IsSinglePrefixBlock returns whether the address range matches the block of values for a single prefix identified by the prefix length of this address.
// This is similar to IsPrefixBlock except that it returns false when the subnet has multiple prefixes.
//
// What distinguishes this method from ContainsSinglePrefixBlock is that this method returns
// false if the series does not have a prefix length assigned to it,
// or a prefix length that differs from the prefix length for which ContainsSinglePrefixBlock returns true.
//
// It is similar to IsPrefixBlock but returns false when there are multiple prefixes.
//
// For instance, "1.*.*.* /16" returns false from this method and returns true from IsPrefixBlock.
func (addr *ipAddressInternal) IsSinglePrefixBlock() bool {
return addr.addressInternal.IsSinglePrefixBlock()
}
// IsPrefixBlock returns whether the address has a prefix length and the address range includes the block of values for that prefix length.
// If the prefix length matches the bit count, this returns true.
//
// To create a prefix block from any address, use ToPrefixBlock.
//
// This is different from ContainsPrefixBlock in that this method returns
// false if the series has no prefix length, or a prefix length that differs from a prefix length for which ContainsPrefixBlock returns true.
func (addr *ipAddressInternal) IsPrefixBlock() bool {
return addr.addressInternal.IsPrefixBlock()
}
// ContainsPrefixBlock returns whether the range of this address or subnet contains the block of addresses for the given prefix length.
//
// Unlike ContainsSinglePrefixBlock, whether there are multiple prefix values in this item for the given prefix length makes no difference.
//
// Use GetMinPrefixLenForBlock to determine the smallest prefix length for which this method returns true.
func (addr *ipAddressInternal) ContainsPrefixBlock(prefixLen BitCount) bool {
return addr.addressInternal.ContainsPrefixBlock(prefixLen)
}
// ContainsSinglePrefixBlock returns whether this address contains a single prefix block for the given prefix length.
//
// This means there is only one prefix value for the given prefix length, and it also contains the full prefix block for that prefix, all addresses with that prefix.
//
// Use GetPrefixLenForSingleBlock to determine whether there is a prefix length for which this method returns true.
func (addr *ipAddressInternal) ContainsSinglePrefixBlock(prefixLen BitCount) bool {
return addr.addressInternal.ContainsSinglePrefixBlock(prefixLen)
}
// GetMinPrefixLenForBlock returns the smallest prefix length such that this includes the block of addresses for that prefix length.
//
// If the entire range can be described this way, then this method returns the same value as GetPrefixLenForSingleBlock.
//
// There may be a single prefix, or multiple possible prefix values in this item for the returned prefix length.
// Use GetPrefixLenForSingleBlock to avoid the case of multiple prefix values.
//
// If this represents just a single address, returns the bit length of this address.
//
// See AssignMinPrefixForBlock for some examples.
func (addr *ipAddressInternal) GetMinPrefixLenForBlock() BitCount {
return addr.addressInternal.GetMinPrefixLenForBlock()
}
// GetPrefixLenForSingleBlock returns a prefix length for which the range of this address subnet matches exactly the block of addresses for that prefix.
//
// If the range can be described this way, then this method returns the same value as GetMinPrefixLenForBlock.
//
// If no such prefix exists, returns nil.
//
// If this segment grouping represents a single value, returns the bit length of this address division series.
//
// IP address examples:
// - 1.2.3.4 returns 32
// - 1.2.3.4/16 returns 32
// - 1.2.*.* returns 16
// - 1.2.*.0/24 returns 16
// - 1.2.0.0/16 returns 16
// - 1.2.*.4 returns nil
// - 1.2.252-255.* returns 22
func (addr *ipAddressInternal) GetPrefixLenForSingleBlock() PrefixLen {
return addr.addressInternal.GetPrefixLenForSingleBlock()
}
func (addr *ipAddressInternal) rangeIterator(
//creator parsedAddressCreator, /* nil for zero sections */
upper *IPAddress,
valsAreMultiple bool,
prefixLen PrefixLen,
segProducer func(addr *IPAddress, index int) *IPAddressSegment,
segmentIteratorProducer func(seg *IPAddressSegment, index int) Iterator[*IPAddressSegment],
segValueComparator func(seg1, seg2 *IPAddress, index int) bool,
networkSegmentIndex,
hostSegmentIndex int,
prefixedSegIteratorProducer func(seg *IPAddressSegment, index int) Iterator[*IPAddressSegment],
) Iterator[*Address] {
//lower := rng.lower
//upper := rng.upper
lower := addr.toIPAddress()
divCount := lower.GetSegmentCount()
// at any given point in time, this list provides an iterator for the segment at each index
segIteratorProducerList := make([]func() Iterator[*IPAddressSegment], divCount)
// at any given point in time, finalValue[i] is true if and only if we have reached the very last value for segment i - 1
// when that happens, the next iterator for the segment at index i will be the last
finalValue := make([]bool, divCount+1)
// here is how the segment iterators will work:
// the low and high values of the range at each segment are low, high
// the maximum possible values for any segment are min, max
// we first find the first k >= 0 such that low != high for the segment at index k
// the initial set of iterators at each index are as follows:
// for i < k finalValue[i] is set to true right away.
// we create an iterator from seg = new Seg(low)
// for i == k we create a wrapped iterator from Seg(low, high), wrapper will set finalValue[i] once we reach the final value of the iterator
// for i > k we create an iterator from Seg(low, max)
//
// after the initial iterator has been supplied, any further iterator supplied for the same segment is as follows:
// for i <= k, there was only one iterator, there will be no further iterator
// for i > k,
// if i == 0 or of if flagged[i - 1] is true, we create a wrapped iterator from Seg(low, high), wrapper will set finalValue[i] once we reach the final value of the iterator
// otherwise we create an iterator from Seg(min, max)
//
// By following these rules, we iterate through all possible addresses
notDiffering := true
finalValue[0] = true
var allSegShared *IPAddressSegment
for i := 0; i < divCount; i++ {
var segIteratorProducer func(seg *IPAddressSegment, index int) Iterator[*IPAddressSegment]
if prefixedSegIteratorProducer != nil && i >= networkSegmentIndex {
segIteratorProducer = prefixedSegIteratorProducer
} else {
segIteratorProducer = segmentIteratorProducer
}
lowerSeg := segProducer(lower, i)
indexi := i
if notDiffering {
notDiffering = segValueComparator(lower, upper, i)
if notDiffering {
// there is only one iterator and it produces only one value
finalValue[i+1] = true
iterator := segIteratorProducer(lowerSeg, i)
segIteratorProducerList[i] = func() Iterator[*IPAddressSegment] { return iterator }
} else {
// in the first differing segment the only iterator will go from segment value of lower address to segment value of upper address
iterator := segIteratorProducer(
createAddressDivision(lowerSeg.deriveNewMultiSeg(lowerSeg.getSegmentValue(), upper.GetGenericSegment(i).GetSegmentValue(), nil)).ToIP(),
i)
wrappedFinalIterator := &wrappedIterator{
iterator: iterator,
finalValue: finalValue,
indexi: indexi,
}
segIteratorProducerList[i] = func() Iterator[*IPAddressSegment] { return wrappedFinalIterator }
}
} else {
// in the second and all following differing segments, rather than go from segment value of lower address to segment value of upper address
// we go from segment value of lower address to the max seg value the first time through
// then we go from the min value of the seg to the max seg value each time until the final time,
// the final time we go from the min value to the segment value of upper address
// we know it is the final time through when the previous iterator has reached its final value, which we track
// the first iterator goes from the segment value of lower address to the max value of the segment
firstIterator := segIteratorProducer(
createAddressDivision(lowerSeg.deriveNewMultiSeg(lowerSeg.getSegmentValue(), lower.GetMaxSegmentValue(), nil)).ToIP(),
i)
// the final iterator goes from 0 to the segment value of our upper address
finalIterator := segIteratorProducer(
createAddressDivision(lowerSeg.deriveNewMultiSeg(0, upper.GetGenericSegment(i).GetSegmentValue(), nil)).ToIP(),
i)
// the wrapper iterator detects when the final iterator has reached its final value
wrappedFinalIterator := &wrappedIterator{
iterator: finalIterator,
finalValue: finalValue,
indexi: indexi,
}
if allSegShared == nil {
allSegShared = createAddressDivision(lowerSeg.deriveNewMultiSeg(0, lower.GetMaxSegmentValue(), nil)).ToIP()
}
// all iterators after the first iterator and before the final iterator go from 0 the max segment value,
// and there will be many such iterators
finalIteratorProducer := func() Iterator[*IPAddressSegment] {
if finalValue[indexi] {
return wrappedFinalIterator
}
return segIteratorProducer(allSegShared, indexi)
}
segIteratorProducerList[i] = func() Iterator[*IPAddressSegment] {
//the first time through, we replace the iterator producer so the first iterator used only once (ie we remove this function from the list)
segIteratorProducerList[indexi] = finalIteratorProducer
return firstIterator
}
}
}
iteratorProducer := func(iteratorIndex int) Iterator[*AddressSegment] {
iter := segIteratorProducerList[iteratorIndex]()
return wrappedSegmentIterator[*IPAddressSegment]{iter}
}
return rangeAddrIterator(
false,
lower.ToAddressBase(),
prefixLen,
valsAreMultiple,
rangeSegmentsIterator(
divCount,
iteratorProducer,
networkSegmentIndex,
hostSegmentIndex,
iteratorProducer,
),
)
}
//// end needed for godoc / pkgsite
var zeroIPAddr = createIPAddress(zeroSection, NoZone)
// IPAddress represents an IP address or subnet, either IPv4 or IPv6 (except for the zero-valued IPAddress which is neither).
// An IP address is composed of range-valued segments and can optionally have an associated prefix length.
// The zero value IPAddress has no segments, neither IPv4 nor IPv6, which is not compatible with zero value for IPv4 or IPv6, those being 0.0.0.0 and :: respectively.
// The zero value is also known as the adaptive zero.
//
// To construct one from a string, use NewIPAddressString,
// then use the ToAddress or GetAddress method of [IPAddressString].
type IPAddress struct {
ipAddressInternal
}
func (addr *IPAddress) init() *IPAddress {
if addr.section == nil {
return zeroIPAddr // this has a zero section
}
return addr
}
func (addr *IPAddress) getProvider() ipAddressProvider {
if addr.IsPrefixed() {
if !addr.IsPrefixBlock() {
return getProviderFor(addr, addr.WithoutPrefixLen())
}
zeroedAddr, _ := addr.toZeroHost(true)
return getProviderFor(addr, zeroedAddr.WithoutPrefixLen())
}
return getProviderFor(addr, addr)
}
// GetCount returns the count of addresses that this address or subnet represents.
//
// If just a single address, not a subnet of multiple addresses, returns 1.
//
// For instance, the IP address subnet "2001:db8::/64" has the count of 2 to the power of 64.
//
// Use IsMultiple if you simply want to know if the count is greater than 1.
func (addr *IPAddress) GetCount() *big.Int {
if addr == nil {
return bigZero()
}
return addr.getCount()
}
// IsMultiple returns true if this represents more than a single individual address, whether it is a subnet of multiple addresses.
func (addr *IPAddress) IsMultiple() bool {
return addr != nil && addr.isMultiple()
}
// Format implements [fmt.Formatter] interface. It accepts the formats
// - 'v' for the default address and section format (either the normalized or canonical string),
// - 's' (string) for the same,
// - 'b' (binary), 'o' (octal with 0 prefix), 'O' (octal with 0o prefix),
// - 'd' (decimal), 'x' (lowercase hexadecimal), and
// - 'X' (uppercase hexadecimal).
// Also supported are some of fmt's format flags for integral types.
// Sign control is not supported since addresses and sections are never negative.
// '#' for an alternate format is supported, which adds a leading zero for octal, and for hexadecimal it adds
// a leading "0x" or "0X" for "%#x" and "%#X" respectively.
// Also supported is specification of minimum digits precision, output field width,
// space or zero padding, and '-' for left or right justification.
func (addr IPAddress) Format(state fmt.State, verb rune) {
addr.init().format(state, verb)
}
// String implements the [fmt.Stringer] interface, returning the canonical string provided by ToCanonicalString, or "<nil>" if the receiver is a nil pointer.
func (addr *IPAddress) String() string {
if addr == nil {
return nilString()
}
return addr.init().ipAddressInternal.toString()
}
// GetSection returns the backing section for this address or subnet, comprising all segments.
func (addr *IPAddress) GetSection() *IPAddressSection {
return addr.init().section.ToIP()
}
// GetTrailingSection gets the subsection from the series starting from the given index.
// The first segment is at index 0.
func (addr *IPAddress) GetTrailingSection(index int) *IPAddressSection {
return addr.GetSection().GetTrailingSection(index)
}
// GetSubSection gets the subsection from the series starting from the given index and ending just before the give endIndex.
// The first segment is at index 0.
func (addr *IPAddress) GetSubSection(index, endIndex int) *IPAddressSection {
return addr.GetSection().GetSubSection(index, endIndex)
}
// GetNetworkSection returns an address section containing the segments with the network of the address or subnet, the prefix bits.
// The returned section will have only as many segments as needed as determined by the existing CIDR network prefix length.
//
// If this series has no CIDR prefix length, the returned network section will
// be the entire series as a prefixed section with prefix length matching the address bit length.
func (addr *IPAddress) GetNetworkSection() *IPAddressSection {
return addr.GetSection().GetNetworkSection()
}
// GetNetworkSectionLen returns a section containing the segments with the network of the address or subnet, the prefix bits according to the given prefix length.
// The returned section will have only as many segments as needed to contain the network.
//
// The new section will be assigned the given prefix length,
// unless the existing prefix length is smaller, in which case the existing prefix length will be retained.
func (addr *IPAddress) GetNetworkSectionLen(prefLen BitCount) *IPAddressSection {
return addr.GetSection().GetNetworkSectionLen(prefLen)
}
// GetHostSection returns a section containing the segments with the host of the address or subnet, the bits beyond the CIDR network prefix length.
// The returned section will have only as many segments as needed to contain the host.
//
// If this series has no prefix length, the returned host section will be the full section.
func (addr *IPAddress) GetHostSection() *IPAddressSection {
return addr.GetSection().GetHostSection()
}
// GetHostSectionLen returns a section containing the segments with the host of the address or subnet, the bits beyond the given CIDR network prefix length.
// The returned section will have only as many segments as needed to contain the host.
func (addr *IPAddress) GetHostSectionLen(prefLen BitCount) *IPAddressSection {
return addr.GetSection().GetHostSectionLen(prefLen)
}
// GetNetworkMask returns the network mask associated with the CIDR network prefix length of this address or subnet.
// If this address or subnet has no prefix length, then the all-ones mask is returned.
func (addr *IPAddress) GetNetworkMask() *IPAddress {
return addr.getNetworkMask(addr.getNetwork())
}
// GetHostMask returns the host mask associated with the CIDR network prefix length of this address or subnet.
// If this address or subnet has no prefix length, then the all-ones mask is returned.
func (addr *IPAddress) GetHostMask() *IPAddress {
return addr.getHostMask(addr.getNetwork())
}
// CopySubSegments copies the existing segments from the given start index until but not including the segment at the given end index,
// into the given slice, as much as can be fit into the slice, returning the number of segments copied.
func (addr *IPAddress) CopySubSegments(start, end int, segs []*IPAddressSegment) (count int) {
return addr.GetSection().CopySubSegments(start, end, segs)
}
// CopySegments copies the existing segments into the given slice,
// as much as can be fit into the slice, returning the number of segments copied.
func (addr *IPAddress) CopySegments(segs []*IPAddressSegment) (count int) {
return addr.GetSection().CopySegments(segs)
}
// GetSegments returns a slice with the address segments. The returned slice is not backed by the same array as this section.
func (addr *IPAddress) GetSegments() []*IPAddressSegment {
return addr.GetSection().GetSegments()
}
// GetSegment returns the segment at the given index.
// The first segment is at index 0.
// GetSegment will panic given a negative index or an index matching or larger than the segment count.
func (addr *IPAddress) GetSegment(index int) *IPAddressSegment {
return addr.getSegment(index).ToIP()
}
// GetSegmentCount returns the segment count, the number of segments in this address.
func (addr *IPAddress) GetSegmentCount() int {
return addr.getDivisionCount()
}