Repository navigation
Expand file tree
/
Copy pathIPAddressSection.java
More file actions
1847 lines (1644 loc) · 65.2 KB
/
Copy pathIPAddressSection.java
File metadata and controls
1847 lines (1644 loc) · 65.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
/*
* Copyright 2017 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
* or at
* https://github.com/seancfoley/IPAddress/blob/master/LICENSE
*
* 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 inet.ipaddr;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.TreeMap;
import java.util.function.BiFunction;
import java.util.function.IntFunction;
import java.util.function.Supplier;
import inet.ipaddr.IPAddress.IPVersion;
import inet.ipaddr.IPAddressSection.WildcardOptions.Wildcards;
import inet.ipaddr.IPAddressTypeNetwork.IPAddressCreator;
import inet.ipaddr.IPAddressTypeNetwork.IPAddressSegmentCreator;
import inet.ipaddr.format.IPAddressDivision;
import inet.ipaddr.format.IPAddressPart;
import inet.ipaddr.format.IPAddressSegmentGrouping;
import inet.ipaddr.format.util.IPAddressPartConfiguredString;
import inet.ipaddr.format.util.IPAddressPartStringCollection;
import inet.ipaddr.format.util.IPAddressPartStringCollection.StringParams;
import inet.ipaddr.format.util.IPAddressPartStringParams;
import inet.ipaddr.format.util.sql.IPAddressSQLTranslator;
import inet.ipaddr.format.util.sql.MySQLTranslator;
import inet.ipaddr.format.util.sql.SQLStringMatcher;
import inet.ipaddr.ipv4.IPv4Address;
/**
* A section of an IPAddress.
*
* It is a series of individual address segments.
* <p>
* IPAddressSection objects are immutable. Some of the derived state is created upon demand and cached.
*
* This also makes them thread-safe.
*
* Almost all operations that can be performed on IPAddress objects can also be performed on IPAddressSection objects and vice-versa.
*
*/
public abstract class IPAddressSection extends IPAddressSegmentGrouping {
private static final long serialVersionUID = 1L;
private static final IPAddressPart EMPTY_PARTS[] = new IPAddressPart[0];
/* the address bytes for the lowest value */
private transient byte[] lowerBytes;
/* caches objects to avoid recomputing them */
protected static class SectionCache {
/* for caching */
private Integer networkMaskPrefixLen; //null indicates this field not initialized, -1 indicates the prefix len is null
private Integer hostMaskPrefixLen; //null indicates this field not initialized, -1 indicates the prefix len is null
/* also for caching */
private Integer cachedMinPrefix; //null indicates this field not initialized
private Integer cachedEquivalentPrefix; //null indicates this field not initialized, -1 indicates the prefix len is null
public IPAddressSection lowerSection;
public IPAddressSection upperSection;
}
protected transient SectionCache sectionCache;
protected IPAddressSection(IPAddressSegment segments[], byte bytes[], boolean cloneSegments, boolean cloneBytes) {
super(cloneSegments ? segments.clone() : segments);
Integer previousSegmentPrefix = null;
for(IPAddressSegment segment : segments) {
if(segment == null) {
throw new NullPointerException("null segment");
}
/**
* Across an address prefixes are:
* IPv6: (null):...:(null):(1 to 16):(0):...:(0)
* or IPv4: ...(null).(1 to 8).(0)...
*/
Integer segPrefix = segment.getSegmentPrefixLength();
if(previousSegmentPrefix != null && (segPrefix == null || segPrefix != 0)) {
throw new IllegalArgumentException("Segments invalid due to inconsistent prefix values");
}
previousSegmentPrefix = segPrefix;
}
if(bytes != null) {
setBytes(cloneBytes ? bytes.clone() : bytes);
}
}
protected static <S extends IPAddressSegment> S[] toSegments(byte bytes[], int segmentCount, int bytesPerSegment, int bitsPerSegment, IPAddressSegmentCreator<S> creator, Integer networkPrefixLength) {
return IPAddress.toSegments(bytes, null, segmentCount, bytesPerSegment, bitsPerSegment, creator, networkPrefixLength);
}
protected static <S extends IPAddressSegment> S[] toCIDRSegments(Integer bits, S segments[], IPAddressSegmentCreator<S> segmentCreator, BiFunction<S, Integer, S> segProducer) {
segments = segments.clone();
if(bits != null) {
for(int i = 0; i < segments.length; i++) {
S seg = segments[i];
int bitCount = seg.getBitCount();
Integer segmentPrefixLength = IPAddressSection.getSegmentPrefixLength(bitCount, bits, i);
segments[i] = segProducer.apply(seg, segmentPrefixLength);
}
}
return segments;
}
protected void initCachedValues(
Integer prefixLen,
boolean network,
Integer cachedNetworkPrefix,
Integer cachedMinPrefix,
Integer cachedEquivalentPrefix,
BigInteger cachedCount,
RangeList zeroSegments,
RangeList zeroRanges) {
if(sectionCache == null) {
sectionCache = new SectionCache();
}
if(network) {
setNetworkMaskPrefix(prefixLen);
} else {
setHostMaskPrefix(prefixLen);
}
super.initCachedValues(cachedNetworkPrefix, cachedCount);
sectionCache.cachedMinPrefix = cachedMinPrefix;
sectionCache.cachedEquivalentPrefix = cachedEquivalentPrefix;
}
protected static RangeList getNoZerosRange() {
return IPAddressSegmentGrouping.getNoZerosRange();
}
protected static RangeList getSingleRange(int index, int len) {
return IPAddressSegmentGrouping.getSingleRange(index, len);
}
public abstract int getBitsPerSegment();
@Override
public int getBitCount() {
return getSegmentCount() * getBitsPerSegment();
}
@Override
public int getByteCount() {
return getSegmentCount() * getBytesPerSegment();
}
public static int bitsPerSegment(IPVersion version) {
return IPAddressSegment.getBitCount(version);
}
public abstract int getBytesPerSegment();
public static int bytesPerSegment(IPVersion version) {
return IPAddressSegment.getBitCount(version);
}
public boolean isIPv4() {
return false;
}
public boolean isIPv6() {
return false;
}
public abstract IPVersion getIPVersion();
protected static int getSegmentIndex(Integer networkPrefixLength, int byteLength, int bytesPerSegment) {
int byteIndex = getByteIndex(networkPrefixLength, byteLength);
return byteIndex / bytesPerSegment;
}
protected static int getByteIndex(Integer networkPrefixLength, int byteLength) {
if(networkPrefixLength == null) {
return byteLength;
}
if(networkPrefixLength < 0 || networkPrefixLength > byteLength * 8) {
throw new IPAddressTypeException(networkPrefixLength, "ipaddress.error.prefixSize");
}
return Math.min((networkPrefixLength - 1) >> 3, byteLength);
}
public abstract int getByteIndex(Integer networkPrefixLength);
public abstract int getSegmentIndex(Integer networkPrefixLength);
protected abstract IPAddressSegmentCreator<?> getSegmentCreator();
protected abstract IPAddressCreator<?, ?, ?> getAddressCreator();
public abstract IPAddressSection getNetworkSection(int networkPrefixLength, boolean withPrefixLength);
public abstract IPAddressSection getNetworkSection(int networkPrefixLength);
//this method is basically checking whether we can return "this" for getNetworkSection
protected boolean isNetworkSection(int networkPrefixLength, boolean withPrefixLength) {
int segmentCount = getSegmentCount();
if(segmentCount == 0) {
return true;
}
int prefixedSegment = getSegmentIndex(networkPrefixLength);
if(prefixedSegment + 1 < segmentCount) {
return false; //not the right number of segments
}
//the segment count matches, now compare the prefixed segment
int lastSegmentIndex = segmentCount - 1;
int bitsPerSegment = getBitsPerSegment();
int segmentPrefixLength = networkPrefixLength - (lastSegmentIndex * bitsPerSegment);
return !getSegment(lastSegmentIndex).isNetworkChangedByPrefix(getSegmentPrefixLength(bitsPerSegment, segmentPrefixLength), withPrefixLength);
}
protected boolean isHostSection(int networkPrefixLength) {
int segmentCount = getSegmentCount();
if(segmentCount == 0) {
return true;
}
if(networkPrefixLength >= getBitsPerSegment()) {
return false;
}
return !getSegment(0).isHostChangedByPrefix(networkPrefixLength);
}
public abstract IPAddressSection getHostSection(int networkPrefixLength);
private Integer checkForPrefixMask(boolean network) {
int front, back;
if(network) {
front = getSegment(0).getMaxSegmentValue();
back = 0;
} else {
back = getSegment(0).getMaxSegmentValue();
front = 0;
}
int prefixLen = 0;
for(int i=0; i < getSegmentCount(); i++) {
IPAddressSegment seg = getSegment(i);
int value = seg.getLowerSegmentValue();
if(value != front) {
Integer segmentPrefixLen = seg.getMaskPrefixLength(network);
if(segmentPrefixLen == null) {
return null;
}
prefixLen += segmentPrefixLen;
for(i++; i < getSegmentCount(); i++) {
value = getSegment(i).getLowerSegmentValue();
if(value != back) {
return null;
}
}
} else {
prefixLen += seg.getBitCount();
}
}
//note that when segments.length == 0, we return 0 as well, since both the host mask and prefix mask are empty (length of 0 bits)
return prefixLen;
}
/**
* If this address section is equivalent to the mask for a CIDR prefix, it returns that prefix length.
* Otherwise, it returns null.
* A CIDR network mask is an address with all 1s in the network section and then all 0s in the host section.
* A CIDR host mask is an address with all 0s in the network section and then all 1s in the host section.
* The prefix length is the length of the network section.
*
* Also, keep in mind that the prefix length returned by this method is not equivalent to the prefix length used to construct this object.
* The prefix length used to construct indicates the network and host portion 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
* portion of any other address. Therefore the two values can be different values, or one can be null while the other is not.
*
* This method applies only to the lower value of the range if this section represents multiple values.
*
* @param network whether to check for a network mask or a host mask
* @return the prefix length corresponding to this mask, or null if this address is not a CIDR prefix mask
*/
public Integer getMaskPrefixLength(boolean network) {
Integer prefixLen;
if(network) {
if(hasNoSectionCache() || (prefixLen = sectionCache.networkMaskPrefixLen) == null) {
prefixLen = setNetworkMaskPrefix(checkForPrefixMask(network));
}
} else {
if(hasNoSectionCache() || (prefixLen = sectionCache.hostMaskPrefixLen) == null) {
prefixLen = setHostMaskPrefix(checkForPrefixMask(network));
}
}
if(prefixLen < 0) {
return null;
}
return prefixLen;
}
private Integer setHostMaskPrefix(Integer prefixLen) {
if(prefixLen == null) {
prefixLen = sectionCache.hostMaskPrefixLen = -1;
} else {
sectionCache.hostMaskPrefixLen = prefixLen;
sectionCache.networkMaskPrefixLen = -1; //cannot be both network and host mask
}
return prefixLen;
}
private Integer setNetworkMaskPrefix(Integer prefixLen) {
if(prefixLen == null) {
prefixLen = sectionCache.networkMaskPrefixLen = -1;
} else {
sectionCache.networkMaskPrefixLen = prefixLen;
sectionCache.hostMaskPrefixLen = -1; //cannot be both network and host mask
}
return prefixLen;
}
protected static <T extends IPAddress, R extends IPAddressSection, S extends IPAddressSegment>
R getNetworkSegments(
R original,
int networkPrefixLength,
int networkSegmentCount,
boolean withPrefixLength,
IPAddressCreator<T, R, S> creator,
BiFunction<Integer, Integer, S> segProducer) {
if(networkPrefixLength < 0 || networkPrefixLength > original.getBitCount()) {
throw new IPAddressTypeException(original, networkPrefixLength, "ipaddress.error.prefixSize");
}
if(original.isNetworkSection(networkPrefixLength, withPrefixLength)) {
return original;
}
int segmentCount = original.getSegmentCount();
int bitsPerSegment = original.getBitsPerSegment();
int totalBits = segmentCount * bitsPerSegment;
if(networkPrefixLength > totalBits) {
return original;
}
S result[] = creator.createSegmentArray(networkSegmentCount);
if(networkSegmentCount > 0) {
for(int i = 0; i < networkSegmentCount; i++) {
Integer prefix = getSegmentPrefixLength(bitsPerSegment, networkPrefixLength, i);
result[i] = segProducer.apply(i, prefix);
}
}
return creator.createSectionInternal(result);
}
protected int getNetworkSegmentCount(int networkPrefixLength) {
if(networkPrefixLength <= 0) {
return 0;
}
int bitsPerSegment = getBitsPerSegment();
int result = (networkPrefixLength + (bitsPerSegment - 1)) / bitsPerSegment;
int segmentCount = getSegmentCount();
if(result > segmentCount) {
return segmentCount;
}
return result;
}
protected static <T extends IPAddress, R extends IPAddressSection, S extends IPAddressSegment>
R getHostSegments(R original, int networkPrefixLength, int networkSegmentCount, IPAddressCreator<T, R, S> creator,
BiFunction<Integer, Integer, S> segProducer) {
if(networkPrefixLength < 0 || networkPrefixLength > original.getBitCount()) {
throw new IPAddressTypeException(original, networkPrefixLength, "ipaddress.error.prefixSize");
}
if(original.isHostSection(networkPrefixLength) || networkPrefixLength <= 0) {
return original;
}
int segmentCount = original.getSegmentCount();
S result[] = creator.createSegmentArray(networkSegmentCount);
if(networkSegmentCount > 0) {
int bitsPerSegment = original.getBitsPerSegment();
for(int i = networkSegmentCount - 1, j = segmentCount - 1; i >= 0; i--, j--) {
Integer prefix = getSegmentPrefixLength(bitsPerSegment, networkPrefixLength, j);
result[i] = segProducer.apply(j, prefix);
}
}
return creator.createSectionInternal(result);
}
protected int getHostSegmentCount(int networkPrefixLength) {
if(networkPrefixLength <= 0) {
return getSegmentCount();
}
int hostBits = getHostBits(networkPrefixLength);
if(hostBits <= 0) {
return 0;
}
int bitsPerSegment = getBitsPerSegment();
return (hostBits + bitsPerSegment - 1) / bitsPerSegment;
}
public Integer getHostBits() {
if(isPrefixed()) {
return getHostBits(getNetworkPrefixLength());
}
return null;
}
private int getHostBits(int networkPrefixLength) {
return getSegmentCount() * getBitsPerSegment() - networkPrefixLength;
}
protected static <T extends IPAddress, R extends IPAddressSection, S extends IPAddressSegment> R getSubnetSegments(
R original,
R maskSection,
Integer networkPrefixLength,
IPAddressCreator<T, R, S> creator,
boolean verifyMask,
IntFunction<S> segProducer,
IntFunction<S> maskSegProducer) {
if(networkPrefixLength != null && (networkPrefixLength < 0 || networkPrefixLength > original.getBitCount())) {
throw new IPAddressTypeException(original, networkPrefixLength, "ipaddress.error.prefixSize");
}
int i=0;
int bitsPerSegment = original.getBitsPerSegment();
for(; i < original.getSegmentCount(); i++) {
Integer segmentPrefixLength = getSegmentPrefixLength(bitsPerSegment, networkPrefixLength, i);
S seg = segProducer.apply(i);
S mask = maskSegProducer.apply(i);
if(seg.isChangedByMask(mask.getLowerSegmentValue(), segmentPrefixLength)) {
S newSegments[] = creator.createSegmentArray(original.getSegmentCount());
original.copySegments(0, i, newSegments, 0);
for(int j = i; j < original.getSegmentCount(); j++) {
segmentPrefixLength = getSegmentPrefixLength(bitsPerSegment, networkPrefixLength, j);
seg = segProducer.apply(j);
mask = maskSegProducer.apply(j);
int maskValue = mask.getLowerSegmentValue();
if(j > i && !seg.isChangedByMask(maskValue, segmentPrefixLength)) {
newSegments[j] = seg;
} else {
if(verifyMask && !seg.isMaskCompatibleWithRange(maskValue, segmentPrefixLength)) {
throw new IPAddressTypeException(seg, mask, "ipaddress.error.maskMismatch");
}
newSegments[j] = creator.createSegment(seg.getLowerSegmentValue() & maskValue, seg.getUpperSegmentValue() & maskValue, segmentPrefixLength);
}
}
return creator.createSectionInternal(newSegments);
}
}
return original;
}
//call this instead of the method below if you already know the networkPrefixLength doesn't extend to the end of the last segment of the section or address
static Integer getSplitSegmentPrefixLength(int bitsPerSegment, Integer networkPrefixLength, int segmentIndex) {
if(networkPrefixLength != null) {
int segmentPrefixLength = networkPrefixLength - (segmentIndex * bitsPerSegment);
return getSegmentPrefixLength(bitsPerSegment, segmentPrefixLength);
}
return null;
}
/**
* Across the address prefixes are:
* IPv6: (null):...:(null):(1 to 16):(0):...:(0)
* or IPv4: ...(null).(1 to 8).(0)...
*/
public static Integer getSegmentPrefixLength(int bitsPerSegment, Integer networkPrefixLength, int segmentIndex) {
if(networkPrefixLength != null) {
int segmentPrefixLength = networkPrefixLength - (segmentIndex * bitsPerSegment);
return getSegmentPrefixLength(bitsPerSegment, segmentPrefixLength);
}
return null;
}
/**
* Across the address prefixes are:
* IPv6: (null):...:(null):(1 to 16):(0):...:(0)
* or IPv4: ...(null).(1 to 8).(0)...
*/
public static Integer getSegmentPrefixLength(int bitsPerSegment, int segmentBits) {
if(segmentBits <= 0) {
return 0; //none of the bits in this segment matter
} else if(segmentBits <= bitsPerSegment) {
return segmentBits;//some of the bits in this segment matter
}
return null; //all the bits in this segment matter
}
static Integer getJoinedSegmentPrefixLength(int bitsPerSegment, Integer highBits, Integer lowBits) {
if(lowBits == null) {
return null;
}
if(lowBits == 0) {
return highBits;
}
return lowBits + bitsPerSegment;
}
public abstract IPAddressNetwork getNetwork();
/**
* @throws IPAddressTypeException if this address does not map to a single address.
* If you want to get subnet bytes or mask bytes, call getLowestBytes
*/
public byte[] getBytes() {
if(isMultiple()) {
throw new IPAddressTypeException(this, "ipaddress.error.unavailable.numeric");
}
return getLowestBytes();
}
/**
* Gets the bytes for the lowest address in the range represented by this address.
*
* @return
*/
public byte[] getLowestBytes() {
if(lowerBytes == null) {
setBytes(getBytesImpl(true));
}
return lowerBytes.clone();
}
void setBytes(byte bytes[]) {
lowerBytes = bytes;
}
private byte[] getBytesImpl(boolean low) {
int bytesPerSegment = getBytesPerSegment();
int byteCount = getSegmentCount() * bytesPerSegment;
byte bytes[] = new byte[byteCount];
for(int i = 0, n = 0; i < byteCount; i += bytesPerSegment, n++) {
IPAddressSegment seg = getSegment(n);
int segmentValue = low ? seg.getLowerSegmentValue() : seg.getUpperSegmentValue();
int k = bytesPerSegment + i;
for(int j = k - 1; ; j--) {
bytes[j] = (byte) (0xff & segmentValue);
if(j <= i) {
break;
}
segmentValue >>= 8;
}
}
return bytes;
}
public int getSegmentCount() {
return getDivisionCount();
}
public IPAddressSegment getSegment(int index) {
return (IPAddressSegment) divisions[index];
}
public void copySegments(int start, int end, IPAddressSegment segs[], int index) {
System.arraycopy (divisions, start, segs, index, end - start);
}
/**
*
* @return whether this section in decimal appears the same as this segment in octal.
* This is true if all the values lies between 0 and 8 (so the octal and decimal values are the same)
*/
public static boolean isDecimalSameAsOctal(boolean checkRange, IPAddressPart part) {
int count = part.getDivisionCount();
for(int i = 0; i < count; i++) {
IPAddressDivision seg = part.getDivision(i);
if(!checkRange ? seg.rangeIsWithin(0, 7) : seg.valueIsWithin(0, 7)) {
return false;
}
}
return true;
}
public boolean isContainedBy(IPAddressSection other) {
return other.contains(this);
}
/**
* @param other
* @return whether this subnet contains the given address section
*/
public boolean contains(IPAddressSection other) {
//check if they are comparable first
if(getSegmentCount() != other.getSegmentCount()) {
return false;
}
for(int i=0; i < getSegmentCount(); i++) {
IPAddressSegment seg = getSegment(i);
if(!seg.contains(other.getSegment(i))) {
return false;
}
if(seg.isPrefixed()) {
//no need to check host section which contains all possible hosts
break;
}
}
return true;
}
/**
* Subtract the give subnet from this subnet, returning an array of sections for the result (the subnets will not be contiguous so an array is required).
*
* Computes the subnet difference, the set of addresses in this address section but not in the provided section.
*
* Keep in mind this is set subtraction, not subtraction of segment values. We have a subnet of addresses and we are removing some of those addresses.
*
* @param other
* @throws IPAddressTypeException if the two sections are not comparable
* @return the difference
*/
public abstract IPAddressSection[] subtract(IPAddressSection other);
protected static <T extends IPAddress, R extends IPAddressSection, S extends IPAddressSegment> R[]
subtract(R first, R other, IPAddressCreator<T, R, S> addrCreator, IntFunction<S> segProducer, BiFunction<R, Integer, R> prefixApplier) {
//check if they are comparable first
int segCount = first.getSegmentCount();
if(segCount != other.getSegmentCount()) {
throw new IPAddressTypeException(first, other, "ipaddress.error.sizeMismatch");
}
if(!first.isMultiple()) {
if(other.contains(first)) {
return null;
}
R result[] = addrCreator.createSectionArray(1);
result[0] = first;
return result;
} else {
//getDifference: same as removing the intersection
// first you confirm there is an intersection in each segment.
// Then you remove each intersection, one at a time, leaving the other segments the same, since only one segment needs to differ.
// To prevent adding the same section twice, use only the intersection (ie the relative complement of the diff) of segments already handled and not the whole segment.
// For example: 0-3.0-3.2.4 subtracting 1-4.1-3.2.4
// The diff of the first segment is just 0, giving 0.0-3.2.4
// The diff of the second segment is also 0, but for the first segment we use the intersection since we handled the first already, giving 1-3.0.2.4
for(int i = 0; i < segCount; i++) {
IPAddressSegment seg = first.getSegment(i);
IPAddressSegment otherSeg = other.getSegment(i);
int lower = seg.getLowerSegmentValue();
int higher = seg.getUpperSegmentValue();
int otherLower = otherSeg.getLowerSegmentValue();
int otherHigher = otherSeg.getUpperSegmentValue();
if(otherLower > higher || lower > otherHigher) {
//no overlap in this segment means no overlap at all
R result[] = addrCreator.createSectionArray(1);
result[0] = first;
return result;
}
}
S intersections[] = addrCreator.createSegmentArray(segCount);
ArrayList<R> sections = new ArrayList<R>();
for(int i = 0; i < segCount; i++) {
S seg = segProducer.apply(i);
IPAddressSegment otherSeg = other.getSegment(i);
int lower = seg.getLowerSegmentValue();
int higher = seg.getUpperSegmentValue();
int otherLower = otherSeg.getLowerSegmentValue();
int otherHigher = otherSeg.getUpperSegmentValue();
if(lower >= otherLower) {
if(higher <= otherHigher) {
//this segment is contained in the other
if(seg.isPrefixed()) {
intersections[i] = addrCreator.createSegment(lower, higher, null);
} else {
intersections[i] = seg;
}
continue;
}
//otherLower <= lower <= otherHigher < higher
intersections[i] = addrCreator.createSegment(lower, otherHigher, null);
R section = createDiffSection(first, otherHigher + 1, higher, i, addrCreator, segProducer, intersections);
sections.add(section);
} else {
//lower < otherLower <= otherHigher
R section = createDiffSection(first, lower, otherLower - 1, i, addrCreator, segProducer, intersections);
sections.add(section);
if(higher <= otherHigher) {
intersections[i] = addrCreator.createSegment(otherLower, higher, null);
} else {
//lower < otherLower <= otherHigher < higher
intersections[i] = addrCreator.createSegment(otherLower, otherHigher, null);
section = createDiffSection(first, otherHigher + 1, higher, i, addrCreator, segProducer, intersections);
sections.add(section);
}
}
}
//apply the prefix to the sections
if(first.isPrefixed()) {
int thisPrefix = first.getNetworkPrefixLength();
for(int i = 0; i < sections.size(); i++) {
R section = sections.get(i);
int bitCount = section.getBitCount();
int totalPrefix = bitCount;
for(int j = first.getSegmentCount() - 1; j >= 0 ; j--) {
IPAddressSegment seg = section.getSegment(j);
int segBitCount = seg.getBitCount();
int segPrefix = seg.getMinPrefix();
if(segPrefix == segBitCount) {
break;
} else {
totalPrefix -= segBitCount;
if(segPrefix != 0) {
totalPrefix += segPrefix;
break;
}
}
}
if(totalPrefix != bitCount) {
if(totalPrefix < thisPrefix) {
totalPrefix = thisPrefix;
}
section = prefixApplier.apply(section, totalPrefix);
sections.set(i, section);
}
}
}
R result[] = addrCreator.createSectionArray(sections.size());
sections.toArray(result);
return result;
}
}
private static <T extends IPAddress, R extends IPAddressSection, S extends IPAddressSegment> R
createDiffSection(R original, int lower, int upper, int diffIndex, IPAddressCreator<T, R, S> addrCreator, IntFunction<S> segProducer, S intersectingValues[]) {
int segCount = original.getSegmentCount();
S segments[] = addrCreator.createSegmentArray(segCount);
for(int j = 0; j < diffIndex; j++) {
segments[j] = intersectingValues[j];
}
S diff = addrCreator.createSegment(lower, upper, null);
segments[diffIndex] = diff;
for(int j = diffIndex + 1; j < segCount; j++) {
segments[j] = segProducer.apply(j);
}
R section = addrCreator.createSectionInternal(segments);
return section;
}
/**
* Returns whether the given mask and prefix combination can be used to generate a subnet.
* See {@link IPAddress#isMaskCompatibleWithRange(IPAddress, Integer)}
*
* @param mask
* @param networkPrefixLength
* @return
*/
public boolean isMaskCompatibleWithRange(IPAddressSection mask, Integer networkPrefixLength) {
IPVersion version = getIPVersion();
if(!version.equals(mask.getIPVersion())) {
throw new IPAddressTypeException(this, mask, "ipaddress.error.typeMismatch");
}
int segmentCount = getSegmentCount();
if(mask.getSegmentCount() != segmentCount) {
throw new IPAddressTypeException(this, mask, "ipaddress.error.sizeMismatch");
}
if(networkPrefixLength != null && (networkPrefixLength < 0 || networkPrefixLength > getBitCount())) {
throw new IPAddressTypeException(this, networkPrefixLength, "ipaddress.error.prefixSize");
}
if(isMultiple() && (networkPrefixLength == null || networkPrefixLength > 0)) {
int bitsPerSegment = getBitsPerSegment();
if(networkPrefixLength == null) {
networkPrefixLength = segmentCount * bitsPerSegment;
}
for(int i = 0; i < segmentCount; i++, networkPrefixLength -= bitsPerSegment) {
Integer segmentPrefix = getSegmentPrefixLength(bitsPerSegment, networkPrefixLength);
IPAddressSegment segment = getSegment(i);
IPAddressSegment maskSegment = mask.getSegment(i);
if(!segment.isMaskCompatibleWithRange(maskSegment.getLowerSegmentValue(), segmentPrefix)) {
return false;
}
}
}
return true;
}
/**
* Creates a subnet address using the given mask.
*/
public abstract IPAddressSection toSubnet(IPAddressSection mask) throws IPAddressTypeException;
/**
* Creates a subnet address using the given CIDR prefix bits.
*/
public abstract IPAddressSection toSubnet(int networkPrefixLength) throws IPAddressTypeException;
protected void checkSubnet(int networkPrefixLength) throws IPAddressTypeException {
if(networkPrefixLength < 0 || networkPrefixLength > getBitCount()) {
throw new IPAddressTypeException(this, networkPrefixLength, "ipaddress.error.prefixSize");
}
}
/**
* Creates a subnet address using the given mask. If networkPrefixLength is non-null, applies the prefix length as well.
* @throws IPAddressTypeException if the mask is not compatible, see {@link IPAddress#isMaskCompatibleWithRange(IPAddress, Integer)}
*/
public abstract IPAddressSection toSubnet(IPAddressSection mask, Integer networkPrefixLength) throws IPAddressTypeException;
protected void checkSubnet(IPAddressSection mask, Integer networkPrefixLength) throws IPAddressTypeException {
int segmentCount = getSegmentCount();
if(mask.getSegmentCount() != segmentCount) {
throw new IPAddressTypeException(this, mask, "ipaddress.error.sizeMismatch");
}
}
/**
* Returns the CIDR address section for which the range of addresses
* in this section is specified using just a single value and a prefix length in the returned section.
*
* Otherwise, returns null.
*
* If this address represents just a single address, this is returned.
*
* @return
*/
public IPAddressSection toPrefixedEquivalent() {
if(!isMultiple()) {
return this;
}
Integer newPrefix = getEquivalentPrefix();
return newPrefix == null ? null : toSubnet(newPrefix);
}
/**
* Constructs an equivalent address section with the smallest CIDR prefix length possible (largest network),
* such that the address represents the exact same range of addresses.
*
* @return
*/
public IPAddressSection toMinimalPrefixed() {
return toSubnet(getMinPrefix());
}
/**
* Return an address section for the network encompassing this address section.
* The bits indicate the number to reduce the network bits in the network address in comparison to this address.
*
* @param prefixLengthDecrement the number to reduce the network bits in order to create a larger network.
* If null, then this method has the same behaviour as toSupernet()
* @return
*/
public IPAddressSection toSupernet(Integer prefixLengthDecrement) {
int newPrefix = getSupernetPrefix(prefixLengthDecrement);
return toSubnet(newPrefix);
}
/**
* Return an address section for the network encompassing this address section,
* with the network portion of the returned address extending to the furthest segment boundary
* located entirely within but not matching the network portion of this address,
* unless the network portion has no bits in which case the same address is returned.
*
* @return the encompassing network
*/
public IPAddressSection toSupernet() {
return toSupernet(null);
}
int getSupernetPrefix(Integer prefixLengthDecrement) {
int bits;
Integer prefix = getNetworkPrefixLength();
if(prefixLengthDecrement == null) {
int bitsPerSegment = getBitsPerSegment();
if(prefix == null) {
bits = bitsPerSegment;
} else {
int adjustment = prefix % bitsPerSegment;
bits = (adjustment > 0) ? adjustment : bitsPerSegment;
}
} else {
bits = prefixLengthDecrement;
}
int newPrefix;
if(prefix == null) {
prefix = getBitCount();
}
if(prefix <= bits) {
newPrefix = 0;
} else {
newPrefix = prefix - bits;
}
return newPrefix;
}
protected boolean hasNoSectionCache() {
if(sectionCache == null) {
synchronized(this) {
if(sectionCache == null) {
sectionCache = new SectionCache();
return true;
}
}
}
return false;
}
/**
* Returns the smallest CIDR prefix possible (largest network),
* such that this address paired with that prefix represents the exact same range of addresses.
*
* @see inet.ipaddr.format.IPAddressDivision#getMaskPrefixLength(boolean)
*
* @return
*/
public int getMinPrefix() {
Integer result;
if(hasNoSectionCache() || (result = sectionCache.cachedMinPrefix) == null) {
int totalPrefix = getBitCount();
for(int i = getSegmentCount() - 1; i >= 0 ; i--) {
IPAddressSegment seg = getSegment(i);
int segBitCount = seg.getBitCount();
int segPrefix = seg.getMinPrefix();
if(segPrefix == segBitCount) {
break;
} else {
totalPrefix -= segBitCount;
if(segPrefix != 0) {
totalPrefix += segPrefix;
break;
}
}
}
sectionCache.cachedMinPrefix = result = totalPrefix;
}
return result;
}
/**
* Returns a prefix length for which the range of this address section can be specified only using the section's lower value and the prefix length
*
* If no such prefix exists, returns null
* If this address section represents a single value, returns the bit length
*
* @return
*/
public Integer getEquivalentPrefix() {
if(!hasNoSectionCache()) {
Integer result = sectionCache.cachedEquivalentPrefix;
if(result != null) {
if(result < 0) {
return null;
}
return result;
}
}
int totalPrefix = 0;
for(int i = 0; i < getSegmentCount(); i++) {
IPAddressSegment seg = getSegment(i);
int segPrefix = seg.getMinPrefix();
if(!seg.isRangeEquivalent(segPrefix)) {
sectionCache.cachedEquivalentPrefix = -1;
return null;
}
if(seg.isPrefixed()) {
return sectionCache.cachedEquivalentPrefix = totalPrefix + segPrefix;
}
if(segPrefix < seg.getBitCount()) {
//remaining segments must be full range or we return null
for(i++; i < getSegmentCount(); i++) {
IPAddressSegment laterSeg = getSegment(i);
if(!laterSeg.isFullRange()) {
sectionCache.cachedEquivalentPrefix = -1;
return null;
}
}
return sectionCache.cachedEquivalentPrefix = totalPrefix + segPrefix;
}
totalPrefix += segPrefix;
}
return sectionCache.cachedEquivalentPrefix = totalPrefix;
}
/**
* If this represents an address section with ranging values, returns an address section representing the lower values of the range
* If this represents an address section with a single value in each segment, returns this.
*
* @return
*/
public abstract IPAddressSection getLowerSection();
/**
* If this represents an address section with ranging values, returns an address section representing the upper values of the range
* If this represents an address section with a single value in each segment, returns this.
*
* @return
*/
public abstract IPAddressSection getUpperSection();
/**
* If this represents an address section with ranging values, returns an array of address segments representing the lower values of the range
* If this represents an address section with a single value in each segment, returns an array containing the segments for this section.
*