-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathIPSubnetcalc.swift
1442 lines (1218 loc) · 46.9 KB
/
IPSubnetcalc.swift
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
//
// IPSubnetcalc.swift
// SubnetCalc
//
// Created by Julien Mulot on 22/11/2020.
//
import Foundation
import Cocoa
//*********************
//Errors for IP format
//*********************
enum SubnetCalcError: Error {
case invalidIPv4(_ info: String)
case invalidIPv4Mask(_ info: String)
case invalidIPv6(_ info: String)
case invalidIPv6Mask(_ info: String)
}
class IPSubnetCalc: NSObject {
//*********
//Constants
//*********
enum Constants {
//private constants
static let NETWORK_BITS_MIN_CLASSLESS:Int = 1
static let NETWORK_BITS_MIN:Int = 8
static let NETWORK_BITS_MAX:Int = 32
//IPv6 constants
static let addr16Full: UInt16 = 0xFFFF
static let addr16Empty: UInt16 = 0x0000
static let defaultIPv6to4Mask: Int = 96
//static let addr128Full: [UInt16] = [addr16Full, addr16Full, addr16Full, addr16Full, addr16Full, addr16Full, addr16Full, addr16Full]
//static let addr128Empty: [UInt16] = [addr16Empty, addr16Empty, addr16Empty, addr16Empty, addr16Empty, addr16Empty, addr16Empty, addr16Empty]
//static let addr16Hex1: UInt16 = 0xF000
//static let addr16Hex2: UInt16 = 0x0F00
//static let addr16Hex3: UInt16 = 0x00F0
//static let addr16Hex4: UInt16 = 0x000F
static let resIPv6Blocks: [String : String] = ["::1/128" : "Loopback Address",
"::/128" : " Unspecified Address",
"::ffff:0:0/96" : "IPv4-mapped Address",
"64:ff9b::/96" : "IPv4-IPv6 Translation",
"64:ff9b:1::/48" : "IPv4-IPv6 Translation",
"100::/64" : "Discard-Only Address Block",
"2001::/23" : "IETF Protocol Assignments",
"2001::/32" : "TEREDO",
"2001:1::1/128" : "Port Control Protocol Anycast",
"2001:1::2/128" : "Traversal Using Relays around NAT Anycast",
"2001:2::/48" : "Benchmarking",
"2001:3::/32" : "AMT",
"2001:4:112::/48" : "AS112-v6",
"2001:10::/28" : "Deprecated (previously ORCHID)",
"2001:20::/28" : "ORCHIDv2",
"2001:db8::/32" : "Documentation",
"2002::/16" : "6to4",
"2620:4f:8000::/48" : "Direct Delegation AS112 Service",
"fc00::/7" : "Unique-Local",
"fe80::/10" : "Link-Local Unicast"
]
//IPv4 constants
static let classAbits: Int = 8
static let classBbits: Int = 16
static let classCbits: Int = 24
static let addr32Full: UInt32 = 0xFFFFFFFF
static let addr32Empty: UInt32 = 0x00000000
static let addr32Digit1: UInt32 = 0xFF000000
static let addr32Digit2: UInt32 = 0x00FF0000
static let addr32Digit3: UInt32 = 0x0000FF00
static let addr32Digit4: UInt32 = 0x000000FF
static let netIdClassA: UInt32 = 0x01000000
static let maskClassA: UInt32 = 0xFF000000
static let netIdClassB: UInt32 = 0x80000000
static let maskClassB: UInt32 = 0xFFFF0000
static let netIdClassC: UInt32 = 0xC0000000
static let maskClassC: UInt32 = 0xFFFFFF00
static let netIdClassD: UInt32 = 0xE0000000
static let maskClassD: UInt32 = 0xF0000000
static let netIdClassE: UInt32 = 0xF0000000
static let maskClassE: UInt32 = 0xF0000000
}
//****************
//Class Properties
//****************
var ipv4Address: String
var maskBits: Int
var ipv6Address: String
var ipv6MaskBits: Int
//*************
//IPv4 SECTION
//*************
/**
Convert an IP address in its binary representation
- Parameters:
- ipAddress: IP address in dotted decimal format like 192.168.1.42
- space: add a space to each decimal
- dotted: add a dot to each decimal
- Returns:
the binary representation of the given IP address
*/
static func binarize(ipAddress: String, space: Bool = false, dotted: Bool = true) -> String? {
var ipAddressBin = [String]()
var binStr = String()
var ipDigits = [String]()
ipDigits = ipAddress.components(separatedBy: ".")
if ipDigits.count != 4 {
return nil
}
for index in 0...3 {
if let ipDigit = Int(ipDigits[index]) {
ipAddressBin.append(String(ipDigit, radix: 2))
}
else {
return nil
}
while (ipAddressBin[index].count < 8) {
ipAddressBin[index].insert("0", at: ipAddressBin[index].startIndex)
}
var digitBin = ipAddressBin[index]
if (space == true) {
digitBin.insert(" ", at: ipAddressBin[index].index(ipAddressBin[index].startIndex, offsetBy: 4))
}
if (index < 3) {
if (dotted == true) {
binStr += digitBin + "."
}
else {
binStr += digitBin
}
}
else {
binStr += digitBin
}
}
return (binStr)
}
/**
Convert the current IPv4 address to its binary representation
- Parameter dotted: add dot to each decimal
- Returns:
the binary representation of the current IP address
*/
func binaryMap(dotted: Bool = true) -> String {
return (IPSubnetCalc.binarize(ipAddress: ipv4Address, space: false, dotted: dotted)!)
}
/**
Convert an IP address in its hexadecimal representation
- Parameters:
- ipAddress: IP address in dotted decimal format like 192.168.1.42
- dotted: add a dot to each decimal
- Returns:
the hexadecimal representation of the given IP address
*/
static func hexarize(ipAddress: String, dotted: Bool = true) -> String? {
var ipDigits = [String]()
var hexIP = String()
var hex4: String
ipDigits = ipAddress.components(separatedBy: ".")
if ipDigits.count != 4 {
return nil
}
for index in 0...3 {
if let ipDigit = Int(ipDigits[index]) {
hex4 = String(format: "%X", ipDigit)
}
else {
return nil
}
if (hex4.count == 1) {
hex4 = "0" + hex4
}
hexIP += hex4
if (index < 3) {
if (dotted == true) {
hexIP += "."
}
}
}
return (hexIP)
}
/**
Convert the current IPv4 address to its hexadecimal representation
- Parameter dotted: add dot to each decimal
- Returns:
the hexadecimal representation of the current IP address
*/
func hexaMap(dotted: Bool = true) -> String {
return (IPSubnetCalc.hexarize(ipAddress: ipv4Address, dotted: dotted)!)
}
/**
Convert an IP address in dotted decimal format to an UInt32 value
- Parameter ipAddress: an IP address in dotted decimal format like 192.168.1.42
- Returns:
a digital IP address in UInt32 format
*/
static func digitize(ipAddress: String) -> UInt32? {
var ipAddressNum: UInt32 = 0
var ipDigits = [String]()
//var ipDigit: Unit32
ipDigits = ipAddress.components(separatedBy: ".")
if ipDigits.count != 4 {
return nil
}
for index in 0...3 {
if let ipDigit = UInt32(ipDigits[index]) {
ipAddressNum += ipDigit << (32 - 8 * (index + 1))
}
else {
return nil
}
}
return (ipAddressNum & Constants.addr32Full)
}
//OLD numerize a String as a Mask bits value to UInt32
/*
static func numerize(maskDigit: String) -> UInt32 {
var maskNum: UInt32 = 0
if (Int(maskDigit) != nil) {
maskNum = (Constants.addr32Full << (32 - Int(maskDigit)!)) & Constants.addr32Full
}
return (maskNum)
}
*/
/**
Convert a mask value in bits to an UInt32 value
- Parameter maskbits: subnet mask bits as in /XX notation
- Returns:
a digital subnet mask in UInt32 format
*/
static func digitize(maskbits: Int) -> UInt32? {
if (maskbits <= Constants.NETWORK_BITS_MAX && maskbits >= Constants.NETWORK_BITS_MIN_CLASSLESS) {
return ((Constants.addr32Full << (32 - maskbits)) & Constants.addr32Full)
}
return nil
}
/**
Convert an IP address in digital format to dotted decimal format
- Parameter ipAddress: IP address in its digital format
- Returns:
a String reprensenting the dotted decimal format of the given IP address
*/
static func dottedDecimal(ipAddress: UInt32) -> String {
var ipDigits = String()
ipDigits.append(String(((ipAddress & Constants.addr32Digit1) >> Constants.classCbits)) + ".")
ipDigits.append(String(((ipAddress & Constants.addr32Digit2) >> Constants.classBbits)) + ".")
ipDigits.append(String(((ipAddress & Constants.addr32Digit3) >> Constants.classAbits)) + ".")
ipDigits.append(String(((ipAddress & Constants.addr32Digit4))))
return (ipDigits)
}
/**
Check if the IP address is a valid IPv4 address
- Parameters:
- ipAddress: IP address in dotted decimal format like 192.168.1.42
- mask: Optionnal subnet mask
- classless: enable class less checks of the given IP address/mask
- Throws: an invalid IP or invalid mask error with a message explaining the reason
*/
static func validateIPv4(ipAddress: String, mask: String?, classless: Bool = false) throws {
var ip4Digits = [String]()
ip4Digits = ipAddress.components(separatedBy: ".")
if (ip4Digits.count == 4) {
for item in ip4Digits {
if let digit = Int(item, radix: 10) {
if (digit > 255) {
print("bad IPv4 digit \(digit)")
throw SubnetCalcError.invalidIPv4("IPv4 digit \(digit) is greater than 255")
//return false
}
}
else {
print("not digit: \(item)")
throw SubnetCalcError.invalidIPv4("not digit: \(item)")
//return false
}
}
}
else {
print("bad IPv4 format \(ip4Digits)")
throw SubnetCalcError.invalidIPv4("\(ipAddress) too short or too long")
//return false
}
if mask != nil {
if let maskNum = Int(mask!) {
if (classless == true) {
if (maskNum < Constants.NETWORK_BITS_MIN_CLASSLESS || maskNum > Constants.NETWORK_BITS_MAX) {
print("IPv4 classless mask \(maskNum) invalid")
throw SubnetCalcError.invalidIPv4Mask("IPv4 classless mask \(maskNum) should be between \(Constants.NETWORK_BITS_MIN_CLASSLESS) and \(Constants.NETWORK_BITS_MAX)")
//return false
}
}
else if (maskNum < Constants.NETWORK_BITS_MIN || maskNum > Constants.NETWORK_BITS_MAX) {
print("IPv4 mask \(maskNum) invalid")
throw SubnetCalcError.invalidIPv4Mask("IPv4 mask \(maskNum) should be between \(Constants.NETWORK_BITS_MIN) and \(Constants.NETWORK_BITS_MAX)")
//return false
}
}
else {
print("IPv4 mask \(mask!) is not digit")
throw SubnetCalcError.invalidIPv4Mask("IPv4 mask \(mask!) is not a digit")
//return false
}
}
else {
//print("null mask")
}
//return true
}
/**
Returns current Subnet ID address
- Returns:
the dotted decimal representation of the Subnet ID of the current IP address/mask
*/
func subnetId() -> String {
var subnetId: UInt32 = 0
let ipBits = IPSubnetCalc.digitize(ipAddress: self.ipv4Address)!
let maskBits = IPSubnetCalc.digitize(maskbits: self.maskBits)!
subnetId = ipBits & maskBits
return (IPSubnetCalc.dottedDecimal(ipAddress: subnetId))
}
/**
Returns current broadcast address
- Returns:
the dotted decimal representation of the broadcast address of the current IP address/mask
*/
func subnetBroadcast() -> String {
var broadcast: UInt32 = 0
let ipBits = IPSubnetCalc.digitize(ipAddress: self.ipv4Address)!
let maskBits = IPSubnetCalc.digitize(maskbits: self.maskBits)!
broadcast = ipBits & maskBits | (Constants.addr32Full >> self.maskBits)
return (IPSubnetCalc.dottedDecimal(ipAddress: broadcast))
}
/**
Returns current Subnet Mask
- Returns:
String of the current subnet mask as in /XX notation
*/
func subnetMask() -> String {
var subnetMask: UInt32 = 0
subnetMask = Constants.addr32Full << (32 - self.maskBits)
return (IPSubnetCalc.dottedDecimal(ipAddress: subnetMask))
}
/**
Returns current Wildcard Subnet Mask
- Returns:
the dotted decimal representation of the wildcard subnet mask of the current IP address/mask
*/
func wildcardMask() -> String {
var wildcardMask: UInt32 = 0
wildcardMask = ~(Constants.addr32Full << (32 - self.maskBits))
return (IPSubnetCalc.dottedDecimal(ipAddress: wildcardMask))
}
/**
Returns the maximum hosts in the current subnet
- Returns:
maximum hosts for the current mask
*/
func maxHosts() -> Int {
var maxHosts: UInt32 = 0
if (self.maskBits == 32) {
return (0)
}
maxHosts = (Constants.addr32Full >> self.maskBits) - 1
return (Int(maxHosts))
}
/**
Returns the maximum CIDR subnets
- Returns:
maximum CIDR subnets for the current mask
*/
func maxCIDRSubnets() -> Int {
var max: Int = 0
max = Int(truncating: NSDecimalNumber(decimal: pow(2, (32 - self.maskBits))))
//max = Int(truncating: pow(2, (32 - self.maskBits)) as NSDecimalNumber)
return (max)
}
/**
Returns the maximum CIDR Supernets
- Returns:
maximum CIDR Supernets for the current mask
*/
func maxCIDRSupernet() -> Int {
let classType = self.netClass()
var result: Decimal
if (classType == "A") {
if (Constants.classAbits - self.maskBits > 0) {
result = pow(2, Constants.classAbits - self.maskBits)
return (Int(truncating: NSDecimalNumber(decimal: result)))
}
}
else if (classType == "B") {
if (Constants.classBbits - self.maskBits > 0) {
result = pow(2, Constants.classBbits - self.maskBits)
return (Int(truncating: NSDecimalNumber(decimal: result)))
}
}
else if (classType == "C") {
if (Constants.classCbits - self.maskBits > 0) {
result = pow(2, Constants.classCbits - self.maskBits)
return (Int(truncating: NSDecimalNumber(decimal: result)))
}
}
return (1)
}
/**
Returns the current subnet IP Range
- Returns:
First IP address - Last IP address of the current IP address/mask
*/
func subnetRange() -> String {
var range = String()
var firstIP: UInt32 = 0
var lastIP: UInt32 = 0
if (maskBits == 31 || maskBits == 32) {
firstIP = IPSubnetCalc.digitize(ipAddress: subnetId())!
lastIP = IPSubnetCalc.digitize(ipAddress: subnetBroadcast())!
}
else {
firstIP = IPSubnetCalc.digitize(ipAddress: subnetId())! + 1
lastIP = IPSubnetCalc.digitize(ipAddress: subnetBroadcast())! - 1
}
range = IPSubnetCalc.dottedDecimal(ipAddress: firstIP) + " - " + IPSubnetCalc.dottedDecimal(ipAddress: lastIP)
return (range)
}
/**
Returns the current CIDR subnet IP Range
- Returns:
First IP address - Last IP address of the current CIDR IP address/mask
*/
func subnetCIDRRange() -> String {
var range = String()
var firstIP: UInt32 = 0
var lastIP: UInt32 = 0
firstIP = IPSubnetCalc.digitize(ipAddress: subnetId())!
lastIP = IPSubnetCalc.digitize(ipAddress: subnetBroadcast())!
range = IPSubnetCalc.dottedDecimal(ipAddress: firstIP) + " - " + IPSubnetCalc.dottedDecimal(ipAddress: lastIP)
return (range)
}
/**
Returns the Network Class of an IP address
- Parameter ipAddress: IPv4 address in dotted decimal format
- Returns:
Network Class conforming to RFC 790
*/
static func netClass(ipAddress: String) -> String? {
if let ipNum = IPSubnetCalc.digitize(ipAddress: ipAddress) {
let addr1stByte = (ipNum & Constants.maskClassA) >> 24
if (addr1stByte < 127) {
return ("A")
}
if (addr1stByte >= 127 && addr1stByte < 192) {
return ("B")
}
if (addr1stByte >= 192 && addr1stByte < 224) {
return ("C")
}
if (addr1stByte >= 224 && addr1stByte < 240) {
return ("D")
}
return ("E")
}
return nil
}
/**
Returns the Network Class of the current IP address
- Returns:
Network Class of the current IP address conforming to RFC 790
*/
func netClass() -> String {
return (IPSubnetCalc.netClass(ipAddress: ipv4Address)!)
}
/**
Returns the bits dedicated to the Subnet part of the IP Address
- Returns:
bits dedicated to the Subnet part of the current IP Address
*/
func subnetBits() -> Int {
let classType = self.netClass()
var bits: Int = 0
if (classType == "A") {
if (self.maskBits > Constants.classAbits) {
bits = self.maskBits - Constants.classAbits
}
}
else if (classType == "B") {
if (self.maskBits > Constants.classBbits) {
bits = self.maskBits - Constants.classBbits
}
}
else if (classType == "C") {
if (self.maskBits > Constants.classCbits) {
bits = self.maskBits - Constants.classCbits
}
}
return (bits)
}
/**
Returns the bits dedicated to Network Class
- Returns:
bits dedicated to the Network Class of the current IP address
*/
func classBits() -> Int {
let classType = self.netClass()
if (classType == "A") {
return (Constants.classAbits)
}
else if (classType == "B") {
return (Constants.classBbits)
}
else if (classType == "C") {
return (Constants.classCbits)
}
return (32)
}
/**
Returns the mask bits for the Network Class
- Returns:
mask bits dedicated for the Network Class of the current IP address
*/
func classMask() -> UInt32 {
let classType = self.netClass()
if (classType == "A") {
return (Constants.maskClassA)
}
else if (classType == "B") {
return (Constants.maskClassB)
}
else if (classType == "C") {
return (Constants.maskClassC)
}
else if (classType == "D") {
return (Constants.maskClassD)
}
else if (classType == "E") {
return (Constants.maskClassE)
}
return (Constants.maskClassE)
}
/**
Returns the number of bits of the mask
- Parameter maskAddr: mask in dotted decimal format
- Returns:
the number of bits for the given mask
*/
static func maskBits(maskAddr: String) -> Int? {
var bits: Int = 0
if var mask:UInt32 = IPSubnetCalc.digitize(ipAddress: maskAddr) {
while (mask != 0) {
bits += 1
mask <<= 1
}
//print("maskBits \(maskAddr) bits: \(bits)")
return (bits)
}
return nil
}
/**
Returns the number of bits of the mask
- Parameter mask: mask in digitize format
- Returns:
the number of bits for the given mask
*/
static func maskBits(mask: UInt32) -> Int {
var bits: Int = 0
var tmpmask = mask
while (tmpmask != 0) {
bits += 1
tmpmask <<= 1
}
//print("maskBits \(mask) bits: \(bits)")
return (bits)
}
/**
Returns the number of bits dedicated to Network
- Returns:
number of bits dedicated to the Network of the current IP address
*/
func netBits() -> Int {
let classType = self.netClass()
var bits: Int = 0
if (classType == "A") {
if (self.maskBits > Constants.classAbits) {
bits = Constants.classAbits
}
else {
bits = self.maskBits
}
}
else if (classType == "B") {
if (self.maskBits > Constants.classBbits) {
bits = Constants.classBbits
}
else {
bits = self.maskBits
}
}
else if (classType == "C") {
if (self.maskBits > Constants.classCbits) {
bits = Constants.classCbits
}
else {
bits = self.maskBits
}
}
return (bits)
}
/**
Returns the maximum number of subnets
- Returns:
maximum number of subnets for the current Subnet bits
*/
func maxSubnets() -> Int {
var maxSubnets: Int = 0
let bits = subnetBits()
maxSubnets = Int(truncating: NSDecimalNumber(decimal: pow(2, bits)))
return (maxSubnets)
}
/**
Returns the Bit Map representation
- Parameter dotted: add dot at each decimal
- Returns:
Bit Map reprensenation of the current ip address/mask
*/
func bitMap(dotted: Bool = true) -> String {
let netBits = self.netBits()
let subnetBits = self.subnetBits()
var bitMap = String()
for index in 0...31 {
if (index < netBits) {
bitMap.append("n")
}
else if (index < (netBits + subnetBits)) {
bitMap.append("s")
}
else {
bitMap.append("h")
}
if ((index < 31) && ((index + 1) % 8 == 0)) {
if (dotted == true) {
bitMap.append(".")
}
}
}
return (bitMap)
}
/**
Returns maskbits and number of max hosts for a requested number of hosts
- Parameter hosts: number of requested hosts
- Returns: maskbits and number of max hosts for the requested number of hosts
*/
static func fittingSubnet(hosts: UInt) -> (Int, UInt) {
var maxHosts: UInt
for index in 1...31 {
maxHosts = UInt(truncating: NSDecimalNumber(decimal: pow(2, index))) - 2
if (hosts <= maxHosts) {
return (32 - index, maxHosts)
}
}
return (0, 0)
}
/**
Display IP informations of the current IP address/mask
*/
func displayIPInfo() {
print("IP Host : " + self.ipv4Address)
print("Mask bits : \(self.maskBits)")
print("Mask : " + self.subnetMask())
print("Subnet bits : \(self.subnetBits())")
print("Subnet ID : " + self.subnetId())
print("Broadcast : " + self.subnetBroadcast())
print("Max Host : \(self.maxHosts())")
print("Max Subnet : \(self.maxSubnets())")
print("Subnet Range : " + self.subnetRange())
print("IP Class Type : " + self.netClass())
print("Hexa IP : " + self.hexaMap())
print("Binary IP : " + self.binaryMap())
print("BitMap : " + self.bitMap())
print("CIDR Netmask : " + self.subnetMask())
print("Wildcard Mask : " + self.wildcardMask())
print("CIDR Max Subnet : \(self.maxCIDRSubnets())")
print("CIDR Max Hosts : \(self.maxHosts())")
print("CIDR Network (Route) : " + self.subnetId())
print("CIDR Net Notation : " + self.subnetId() + "/" + String(self.maskBits))
print("CIDR Address Range : " + self.subnetCIDRRange())
print("IP number in binary : " + String(IPSubnetCalc.digitize(ipAddress: self.ipv4Address)!, radix: 2))
print("Mask bin : " + String(IPSubnetCalc.digitize(maskbits: self.maskBits)!, radix: 2))
//print("Subnet ID bin : " + String(self.subnetId(), radix: 2))
//print("Broadcast bin : " + String(self.subnetBroadcast(), radix: 2))
}
//*************
//IPv6 SECTION
//*************
/**
Check if the IP address is a valid IPv6 address
- Parameters:
- ipAddress: IPv6 address in hexadecimal format
- mask: Optionnal subnet mask
- Returns:
Boolean if the given IPv6 address is valid or not
*/
static func validateIPv6(ipAddress: String, mask: Int?) throws {
var ip4Hex: [String]?
var hex: UInt16?
if mask != nil {
if (mask! < 1 || mask! > 128) {
print("mask \(mask!) invalid")
throw SubnetCalcError.invalidIPv6Mask("mask \(mask!) must be between 1 and 128")
}
}
else {
//print("null mask")
}
ip4Hex = ipAddress.components(separatedBy: ":")
if (ip4Hex == nil) {
//print("\(ipAddress) invalid")
throw SubnetCalcError.invalidIPv6("IPv6 address must contain :")
}
if (ip4Hex!.count != 8) {
//print("no 8 hex")
if (ipAddress.contains("::"))
{
if (ipAddress.components(separatedBy: "::").count > 2) {
//print("too many '::'")
throw SubnetCalcError.invalidIPv6("too many ::")
}
}
else {
//print("IPv6 \(ipAddress) bad format")
throw SubnetCalcError.invalidIPv6("short IPv6 address must contain ::")
}
}
for index in 0...(ip4Hex!.count - 1) {
//print("Index : \(index) IPHex : \(ip4Hex[index]) Dec : \(String(UInt16(ip4Hex[index], radix: 16)!, radix: 16))")
if (ip4Hex![index].count > 4 && ip4Hex![index].count != 0) {
//print("\(ip4Hex![index]) too large")
throw SubnetCalcError.invalidIPv6("\(ip4Hex![index]) segment is too large")
}
hex = UInt16(ip4Hex![index], radix: 16)
if hex != nil {
if (hex! < 0 || hex! > 0xFFFF) {
//print("\(hex!) is invalid")
throw SubnetCalcError.invalidIPv6("\(hex!) segment must be between 0 and 0xFFFF")
}
}
else {
if (ip4Hex![index] != "") {
//print("\(ip4Hex![index]) not an integer")
throw SubnetCalcError.invalidIPv6("\(ip4Hex![index]) segment is not an integer")
}
}
}
//return true
}
/**
Convert an IPv4 address to its IPv6 address
- Parameters:
- ipAddress: IPv4 address in dotted decimal format
- _6to4: Use 6to4 representation
- Returns:
translated IPv6 address
*/
static func convertIPv4toIPv6(ipAddress: String, _6to4: Bool = false) -> String {
var ipv6str = String()
if let addr = digitize(ipAddress: ipAddress) {
ipv6str.append(String((((Constants.addr32Digit1 | Constants.addr32Digit2) & addr) >> 16), radix: 16))
ipv6str.append(":")
ipv6str.append(String(((Constants.addr32Digit3 | Constants.addr32Digit4) & addr), radix: 16))
if (_6to4)
{
return ("2002:" + ipv6str + ":0:0:0:0:0")
}
return ("0:0:0:0:0:ffff:" + ipv6str)
}
else {
return ""
}
}
/**
Convert an IPv6 address to its IPv4 address
- Parameter ipAddress: IPv6 address in hexadecimal format
- Returns:
translated IPv4 address and detected translation method (6to4 or IPv4-Mapped)
*/
static func convertIPv6toIPv4(ipAddress: String) -> (String, String) {
var ipv4str = String()
//let ip4Hex = fullAddressIPv6(ipAddress: ipAddress).components(separatedBy: ":")
let ip4Hex = ipAddress.components(separatedBy: ":")
let index = ip4Hex.count
if (ip4Hex[0] == "2002") {
if (index > 2) {
if (ip4Hex[1] == "") {
ipv4str.append("0.0")
}
else {
ipv4str.append(String((UInt32(ip4Hex[1], radix: 16)! & Constants.addr32Digit3) >> 8))
ipv4str.append("." + String((UInt32(ip4Hex[1], radix: 16)! & Constants.addr32Digit4)))
}
if (ip4Hex[2] == "") {
ipv4str.append(".0.0")
}
else {
ipv4str.append("." + String((UInt32(ip4Hex[2], radix: 16)! & Constants.addr32Digit3) >> 8))
ipv4str.append("." + String((UInt32(ip4Hex[2], radix: 16)! & Constants.addr32Digit4)))
}
}
return (ipv4str, "6to4")
}
else {
if (index < 2) {
ipv4str.append("0.0")
}
else {
if (ip4Hex[index - 2] == "") {
ipv4str.append("0.0")
}
else {
ipv4str.append(String((UInt32(ip4Hex[index - 2], radix: 16)! & Constants.addr32Digit3) >> 8))
ipv4str.append("." + String((UInt32(ip4Hex[index - 2], radix: 16)! & Constants.addr32Digit4)))
}
}
if (ip4Hex[index - 1] == "") {
ipv4str.append(".0.0")
}
else {
ipv4str.append("." + String((UInt32(ip4Hex[index - 1], radix: 16)! & Constants.addr32Digit3) >> 8))
ipv4str.append("." + String((UInt32(ip4Hex[index - 1], radix: 16)! & Constants.addr32Digit4)))
}
return (ipv4str, "IPv4-Mapped")
}
}
/**
Convert an IPv6 address in hexadecimal format to its digital format
- Parameter ipAddress: an IPv6 address in hexadecimal format. Must be in full format.
- Returns:
UInt16 array of each digitized IPv6 address hexa segments
*/
static func digitizeIPv6(ipAddress: String) -> [UInt16] {
var ipAddressNum: [UInt16] = Array(repeating: 0, count: 8)
var ip4Hex = [String]()
ip4Hex = IPSubnetCalc.fullAddressIPv6(ipAddress: ipAddress).components(separatedBy: ":")
for index in 0...(ip4Hex.count - 1) {
if (ip4Hex[index] == "") {
ip4Hex[index] = "0"
}
ipAddressNum[index] = UInt16(ip4Hex[index], radix: 16)!
//print("Index: \(index) Ip4Hex: \(ip4Hex[index]) Hexa : \(UInt16(ip4Hex[index], radix: 16)!)")
}
return (ipAddressNum)
}
/**