forked from apache/cloudstack
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNetUtils.java
More file actions
1550 lines (1342 loc) · 54.1 KB
/
Copy pathNetUtils.java
File metadata and controls
1550 lines (1342 loc) · 54.1 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
//
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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 com.cloud.utils.net;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URI;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.lang.SystemUtils;
import org.apache.commons.net.util.SubnetUtils;
import org.apache.commons.validator.routines.InetAddressValidator;
import org.apache.log4j.Logger;
import com.cloud.utils.IteratorUtil;
import com.cloud.utils.Pair;
import com.cloud.utils.script.Script;
import com.googlecode.ipv6.IPv6Address;
import com.googlecode.ipv6.IPv6AddressRange;
import com.googlecode.ipv6.IPv6Network;
public class NetUtils {
protected final static Logger s_logger = Logger.getLogger(NetUtils.class);
private static final int MAX_CIDR = 32;
private static final int RFC_3021_31_BIT_CIDR = 31;
public final static String HTTP_PORT = "80";
public final static String HTTPS_PORT = "443";
public final static int VPN_PORT = 500;
public final static int VPN_NATT_PORT = 4500;
public final static int VPN_L2TP_PORT = 1701;
public final static int HAPROXY_STATS_PORT = 8081;
public final static String UDP_PROTO = "udp";
public final static String TCP_PROTO = "tcp";
public final static String ANY_PROTO = "any";
public final static String ICMP_PROTO = "icmp";
public final static String ALL_PROTO = "all";
public final static String HTTP_PROTO = "http";
public final static String SSL_PROTO = "ssl";
public final static String ALL_CIDRS = "0.0.0.0/0";
public final static int PORT_RANGE_MIN = 0;
public final static int PORT_RANGE_MAX = 65535;
public final static int DEFAULT_AUTOSCALE_VM_DESTROY_TIME = 2 * 60; // Grace period before Vm is destroyed
public final static int DEFAULT_AUTOSCALE_POLICY_INTERVAL_TIME = 30;
public final static int DEFAULT_AUTOSCALE_POLICY_QUIET_TIME = 5 * 60;
private final static Random s_rand = new Random(System.currentTimeMillis());
public static long createSequenceBasedMacAddress(final long macAddress) {
return macAddress | 0x060000000000l | (long)s_rand.nextInt(32768) << 25 & 0x00fffe000000l;
}
public static String getHostName() {
try {
final InetAddress localAddr = InetAddress.getLocalHost();
if (localAddr != null) {
return localAddr.getHostName();
}
} catch (final UnknownHostException e) {
s_logger.warn("UnknownHostException when trying to get host name. ", e);
}
return "localhost";
}
public static InetAddress getLocalInetAddress() {
try {
return InetAddress.getLocalHost();
} catch (final UnknownHostException e) {
s_logger.warn("UnknownHostException in getLocalInetAddress().", e);
return null;
}
}
public static String resolveToIp(final String host) {
try {
final InetAddress addr = InetAddress.getByName(host);
return ipFromInetAddress(addr);
} catch (final UnknownHostException e) {
s_logger.warn("Unable to resolve " + host + " to IP due to UnknownHostException");
return null;
}
}
public static InetAddress[] getAllLocalInetAddresses() {
final List<InetAddress> addrList = new ArrayList<InetAddress>();
try {
for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
if (ifc.isUp() && !ifc.isVirtual()) {
for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
addrList.add(addr);
}
}
}
} catch (final SocketException e) {
s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
}
final InetAddress[] addrs = new InetAddress[addrList.size()];
if (addrList.size() > 0) {
System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
}
return addrs;
}
public static String[] getLocalCidrs() {
final String defaultHostIp = getDefaultHostIp();
final List<String> cidrList = new ArrayList<String>();
try {
for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
if (ifc.isUp() && !ifc.isVirtual() && !ifc.isLoopback()) {
for (final InterfaceAddress address : ifc.getInterfaceAddresses()) {
final InetAddress addr = address.getAddress();
final int prefixLength = address.getNetworkPrefixLength();
if (prefixLength < MAX_CIDR && prefixLength > 0) {
final String ip = ipFromInetAddress(addr);
if (ip.equalsIgnoreCase(defaultHostIp)) {
cidrList.add(ipAndNetMaskToCidr(ip, getCidrNetmask(prefixLength)));
}
}
}
}
}
} catch (final SocketException e) {
s_logger.warn("UnknownHostException in getLocalCidrs().", e);
}
return cidrList.toArray(new String[0]);
}
public static String getDefaultHostIp() {
if (SystemUtils.IS_OS_WINDOWS) {
final Pattern pattern = Pattern.compile("\\s*0.0.0.0\\s*0.0.0.0\\s*(\\S*)\\s*(\\S*)\\s*");
try {
final Process result = Runtime.getRuntime().exec("route print -4");
final BufferedReader output = new BufferedReader(new InputStreamReader(result.getInputStream()));
String line = output.readLine();
while (line != null) {
final Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
return matcher.group(2);
}
line = output.readLine();
}
} catch (final IOException e) {
s_logger.debug("Caught IOException", e);
}
return null;
} else {
NetworkInterface nic = null;
final String pubNic = getDefaultEthDevice();
if (pubNic == null) {
return null;
}
try {
nic = NetworkInterface.getByName(pubNic);
} catch (final SocketException e) {
return null;
}
String[] info = null;
try {
info = NetUtils.getNetworkParams(nic);
} catch (final NullPointerException ignored) {
s_logger.debug("Caught NullPointerException when trying to getDefaultHostIp");
}
if (info != null) {
return info[0];
}
return null;
}
}
public static String getDefaultEthDevice() {
if (SystemUtils.IS_OS_MAC) {
final String defDev = Script.runSimpleBashScript("/sbin/route -n get default 2> /dev/null | grep interface | awk '{print $2}'");
return defDev;
}
final String defaultRoute = Script.runSimpleBashScript("/sbin/route | grep default");
if (defaultRoute == null) {
return null;
}
final String[] defaultRouteList = defaultRoute.split("\\s+");
if (defaultRouteList.length != 8) {
return null;
}
return defaultRouteList[7];
}
public static InetAddress getFirstNonLoopbackLocalInetAddress() {
final InetAddress[] addrs = getAllLocalInetAddresses();
if (addrs != null) {
for (final InetAddress addr : addrs) {
if (s_logger.isInfoEnabled()) {
s_logger.info("Check local InetAddress : " + addr.toString() + ", total count :" + addrs.length);
}
if (!addr.isLoopbackAddress()) {
return addr;
}
}
}
s_logger.warn("Unable to determine a non-loopback address, local inet address count :" + addrs.length);
return null;
}
public static InetAddress[] getInterfaceInetAddresses(final String ifName) {
final List<InetAddress> addrList = new ArrayList<InetAddress>();
try {
for (final NetworkInterface ifc : IteratorUtil.enumerationAsIterable(NetworkInterface.getNetworkInterfaces())) {
if (ifc.isUp() && !ifc.isVirtual() && ifc.getName().equals(ifName)) {
for (final InetAddress addr : IteratorUtil.enumerationAsIterable(ifc.getInetAddresses())) {
addrList.add(addr);
}
}
}
} catch (final SocketException e) {
s_logger.warn("SocketException in getAllLocalInetAddresses().", e);
}
final InetAddress[] addrs = new InetAddress[addrList.size()];
if (addrList.size() > 0) {
System.arraycopy(addrList.toArray(), 0, addrs, 0, addrList.size());
}
return addrs;
}
public static String getLocalIPString() {
final InetAddress addr = getLocalInetAddress();
if (addr != null) {
return ipFromInetAddress(addr);
}
return "127.0.0.1";
}
public static String ipFromInetAddress(final InetAddress addr) {
assert addr != null;
final byte[] ipBytes = addr.getAddress();
final StringBuffer sb = new StringBuffer();
sb.append(ipBytes[0] & 0xff).append(".");
sb.append(ipBytes[1] & 0xff).append(".");
sb.append(ipBytes[2] & 0xff).append(".");
sb.append(ipBytes[3] & 0xff);
return sb.toString();
}
public static boolean isLocalAddress(final InetAddress addr) {
final InetAddress[] addrs = getAllLocalInetAddresses();
if (addrs != null) {
for (final InetAddress self : addrs) {
if (self.equals(addr)) {
return true;
}
}
}
return false;
}
public static boolean isLocalAddress(final String strAddress) {
InetAddress addr;
try {
addr = InetAddress.getByName(strAddress);
return isLocalAddress(addr);
} catch (final UnknownHostException e) {
}
return false;
}
public static String getMacAddress(final InetAddress address) {
final StringBuffer sb = new StringBuffer();
final Formatter formatter = new Formatter(sb);
try {
final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
final byte[] mac = ni.getHardwareAddress();
for (int i = 0; i < mac.length; i++) {
formatter.format("%02X%s", mac[i], i < mac.length - 1 ? ":" : "");
}
} catch (final SocketException e) {
s_logger.error("SocketException when trying to retrieve MAC address", e);
} finally {
formatter.close();
}
return sb.toString();
}
public static long getMacAddressAsLong(final InetAddress address) {
long macAddressAsLong = 0;
try {
final NetworkInterface ni = NetworkInterface.getByInetAddress(address);
final byte[] mac = ni.getHardwareAddress();
for (int i = 0; i < mac.length; i++) {
macAddressAsLong |= (long)(mac[i] & 0xff) << (mac.length - i - 1) * 8;
}
} catch (final SocketException e) {
s_logger.error("SocketException when trying to retrieve MAC address", e);
}
return macAddressAsLong;
}
/**
* This method will fail in case we have a 31 Bit prefix network
* See RFC 3021.
*
* In order to avoid calling this method, please check the <code>NetUtils.is31PrefixCidr(cidr)</code> first.
*/
public static boolean ipRangesOverlap(final String startIp1, final String endIp1, final String startIp2, final String endIp2) {
final long startIp1Long = ip2Long(startIp1);
long endIp1Long = startIp1Long;
if (endIp1 != null) {
endIp1Long = ip2Long(endIp1);
}
final long startIp2Long = ip2Long(startIp2);
long endIp2Long = startIp2Long;
if (endIp2 != null) {
endIp2Long = ip2Long(endIp2);
}
if (startIp1Long == startIp2Long || startIp1Long == endIp2Long || endIp1Long == startIp2Long || endIp1Long == endIp2Long) {
return true;
} else if (startIp1Long > startIp2Long && startIp1Long < endIp2Long) {
return true;
} else if (endIp1Long > startIp2Long && endIp1Long < endIp2Long) {
return true;
} else if (startIp2Long > startIp1Long && startIp2Long < endIp1Long) {
return true;
} else if (endIp2Long > startIp1Long && endIp2Long < endIp1Long) {
return true;
} else {
return false;
}
}
public static long ip2Long(final String ip) {
final String[] tokens = ip.split("[.]");
assert tokens.length == 4;
long result = 0;
for (int i = 0; i < tokens.length; i++) {
try {
result = result << 8 | Integer.parseInt(tokens[i]);
} catch (final NumberFormatException e) {
throw new RuntimeException("Incorrect number", e);
}
}
return result;
}
public static String long2Ip(final long ip) {
final StringBuilder result = new StringBuilder(15);
result.append(ip >> 24 & 0xff).append(".");
result.append(ip >> 16 & 0xff).append(".");
result.append(ip >> 8 & 0xff).append(".");
result.append(ip & 0xff);
return result.toString();
}
public static long mac2Long(final String macAddress) {
final String[] tokens = macAddress.split(":");
assert tokens.length == 6;
long result = 0;
for (int i = 0; i < tokens.length; i++) {
result = result << 8;
result |= Integer.parseInt(tokens[i], 16);
}
return result;
}
public static String[] getNicParams(final String nicName) {
try {
final NetworkInterface nic = NetworkInterface.getByName(nicName);
return getNetworkParams(nic);
} catch (final SocketException e) {
return null;
}
}
public static String[] getNetworkParams(final NetworkInterface nic) {
final List<InterfaceAddress> addrs = nic.getInterfaceAddresses();
if (addrs == null || addrs.size() == 0) {
return null;
}
InterfaceAddress addr = null;
for (final InterfaceAddress iaddr : addrs) {
final InetAddress inet = iaddr.getAddress();
if (!inet.isLinkLocalAddress() && !inet.isLoopbackAddress() && !inet.isMulticastAddress() && inet.getAddress().length == 4) {
addr = iaddr;
break;
}
}
if (addr == null) {
return null;
}
final String[] result = new String[3];
result[0] = addr.getAddress().getHostAddress();
try {
final byte[] mac = nic.getHardwareAddress();
result[1] = byte2Mac(mac);
} catch (final SocketException e) {
s_logger.debug("Caught exception when trying to get the mac address ", e);
}
result[2] = prefix2Netmask(addr.getNetworkPrefixLength());
return result;
}
public static String prefix2Netmask(final short prefix) {
long addr = 0;
for (int i = 0; i < prefix; i++) {
addr = addr | 1 << 31 - i;
}
return long2Ip(addr);
}
public static String byte2Mac(final byte[] m) {
final StringBuilder result = new StringBuilder(17);
final Formatter formatter = new Formatter(result);
formatter.format("%02x:%02x:%02x:%02x:%02x:%02x", m[0], m[1], m[2], m[3], m[4], m[5]);
formatter.close();
return result.toString();
}
public static String long2Mac(final long macAddress) {
final StringBuilder result = new StringBuilder(17);
try (Formatter formatter = new Formatter(result)) {
formatter.format("%02x:%02x:%02x:%02x:%02x:%02x",
macAddress >> 40 & 0xff, macAddress >> 32 & 0xff,
macAddress >> 24 & 0xff, macAddress >> 16 & 0xff,
macAddress >> 8 & 0xff, macAddress & 0xff);
}
return result.toString();
}
public static boolean isValidPrivateIp(final String ipAddress, final String guestIPAddress) {
final InetAddress privIp = parseIpAddress(ipAddress);
if (privIp == null) {
return false;
}
if (!privIp.isSiteLocalAddress()) {
return false;
}
String firstGuestOctet = "10";
if (guestIPAddress != null && !guestIPAddress.isEmpty()) {
final String[] guestIPList = guestIPAddress.split("\\.");
firstGuestOctet = guestIPList[0];
}
final String[] ipList = ipAddress.split("\\.");
if (!ipList[0].equals(firstGuestOctet)) {
return false;
}
return true;
}
public static boolean isSiteLocalAddress(final String ipAddress) {
if (ipAddress == null) {
return false;
} else {
final InetAddress ip = parseIpAddress(ipAddress);
if(ip != null) {
return ip.isSiteLocalAddress();
}
return false;
}
}
public static boolean validIpRange(final String startIP, final String endIP) {
if (endIP == null || endIP.isEmpty()) {
return true;
}
final long startIPLong = NetUtils.ip2Long(startIP);
final long endIPLong = NetUtils.ip2Long(endIP);
return startIPLong <= endIPLong;
}
public static boolean isValidIp(final String ip) {
final InetAddressValidator validator = InetAddressValidator.getInstance();
return validator.isValidInet4Address(ip);
}
public static boolean is31PrefixCidr(final String cidr) {
final boolean isValidCird = isValidCIDR(cidr);
if (isValidCird){
final String[] cidrPair = cidr.split("\\/");
final String cidrSize = cidrPair[1];
final int cidrSizeNum = Integer.parseInt(cidrSize);
if (cidrSizeNum == RFC_3021_31_BIT_CIDR) {
return true;
}
}
return false;
}
public static boolean isValidCIDR(final String cidr) {
if (cidr == null || cidr.isEmpty()) {
return false;
}
final String[] cidrPair = cidr.split("\\/");
if (cidrPair.length != 2) {
return false;
}
final String cidrAddress = cidrPair[0];
final String cidrSize = cidrPair[1];
if (!isValidIp(cidrAddress)) {
return false;
}
int cidrSizeNum = -1;
try {
cidrSizeNum = Integer.parseInt(cidrSize);
} catch (final Exception e) {
return false;
}
if (cidrSizeNum < 0 || cidrSizeNum > MAX_CIDR) {
return false;
}
return true;
}
public static boolean isValidNetmask(final String netmask) {
if (!isValidIp(netmask)) {
return false;
}
final long ip = ip2Long(netmask);
int count = 0;
boolean finished = false;
for (int i = 31; i >= 0; i--) {
if ((ip >> i & 0x1) == 0) {
finished = true;
} else {
if (finished) {
return false;
}
count += 1;
}
}
if (count == 0) {
return false;
}
return true;
}
private static InetAddress parseIpAddress(final String address) {
final StringTokenizer st = new StringTokenizer(address, ".");
final byte[] bytes = new byte[4];
if (st.countTokens() == 4) {
try {
for (int i = 0; i < 4; i++) {
bytes[i] = (byte)Integer.parseInt(st.nextToken());
}
return InetAddress.getByAddress(address, bytes);
} catch (final NumberFormatException nfe) {
return null;
} catch (final UnknownHostException uhe) {
return null;
}
}
return null;
}
public static String getCidrFromGatewayAndNetmask(final String gatewayStr, final String netmaskStr) {
final long netmask = ip2Long(netmaskStr);
final long gateway = ip2Long(gatewayStr);
final long firstPart = gateway & netmask;
final long size = getCidrSize(netmaskStr);
return long2Ip(firstPart) + "/" + size;
}
public static String[] getIpRangeFromCidr(final String cidr, final long size) {
assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
final String[] result = new String[2];
final long ip = ip2Long(cidr);
final long startNetMask = ip2Long(getCidrNetmask(size));
final long start = (ip & startNetMask) + 1;
long end = start;
end = end >> MAX_CIDR - size;
end++;
end = (end << MAX_CIDR - size) - 2;
result[0] = long2Ip(start);
result[1] = long2Ip(end);
return result;
}
public static Set<Long> getAllIpsFromCidr(final String cidr, final long size, final Set<Long> usedIps) {
assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
final Set<Long> result = new TreeSet<Long>();
final long ip = ip2Long(cidr);
final long startNetMask = ip2Long(getCidrNetmask(size));
long start = (ip & startNetMask) + 1;
long end = start;
end = end >> MAX_CIDR - size;
end++;
end = (end << MAX_CIDR - size) - 2;
int maxIps = 255; // get 255 ips as maximum
while (start <= end && maxIps > 0) {
if (!usedIps.contains(start)) {
result.add(start);
maxIps--;
}
start++;
}
return result;
}
/**
* Given a cidr, this method returns an ip address within the range but
* is not in the avoid list.
*
* @param startIp ip that the cidr starts with
* @param size size of the cidr
* @param avoid set of ips to avoid
* @return ip that is within the cidr range but not in the avoid set. -1 if unable to find one.
*/
public static long getRandomIpFromCidr(final String startIp, final int size, final SortedSet<Long> avoid) {
return getRandomIpFromCidr(ip2Long(startIp), size, avoid);
}
/**
* Given a cidr, this method returns an ip address within the range but
* is not in the avoid list.
* Note: the gateway address has to be specified in the avoid list
*
* @param cidr ip that the cidr starts with
* @param size size of the cidr
* @param avoid set of ips to avoid
* @return ip that is within the cidr range but not in the avoid set. -1 if unable to find one.
*/
public static long getRandomIpFromCidr(final long cidr, final int size, final SortedSet<Long> avoid) {
assert size < MAX_CIDR : "You do know this is not for ipv6 right? Keep it smaller than 32 but you have " + size;
final long startNetMask = ip2Long(getCidrNetmask(size));
final long startIp = (cidr & startNetMask) + 1; //exclude the first ip since it isnt valid, e.g., 192.168.10.0
int range = 1 << MAX_CIDR - size; //e.g., /24 = 2^8 = 256
range = range - 1; //exclude end of the range since that is the broadcast address, e.g., 192.168.10.255
if (avoid.size() >= range) {
return -1;
}
//Reduce the range by the size of the avoid set
//e.g., cidr = 192.168.10.0, size = /24, avoid = 192.168.10.1, 192.168.10.20, 192.168.10.254
// range = 2^8 - 1 - 3 = 252
range = range - avoid.size();
final int next = s_rand.nextInt(range); //note: nextInt excludes last value
long ip = startIp + next;
for (final Long avoidable : avoid) {
if (ip >= avoidable) {
ip++;
} else {
break;
}
}
return ip;
}
public static String getIpRangeStartIpFromCidr(final String cidr, final long size) {
final long ip = ip2Long(cidr);
final long startNetMask = ip2Long(getCidrNetmask(size));
final long start = (ip & startNetMask) + 1;
return long2Ip(start);
}
public static String getIpRangeEndIpFromCidr(final String cidr, final long size) {
final long ip = ip2Long(cidr);
final long startNetMask = ip2Long(getCidrNetmask(size));
final long start = (ip & startNetMask) + 1;
long end = start;
end = end >> MAX_CIDR - size;
end++;
end = (end << MAX_CIDR - size) - 2;
return long2Ip(end);
}
public static boolean sameSubnet(final String ip1, final String ip2, final String netmask) {
if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
return true;
}
final String subnet1 = NetUtils.getSubNet(ip1, netmask);
final String subnet2 = NetUtils.getSubNet(ip2, netmask);
return subnet1.equals(subnet2);
}
public static boolean sameSubnetCIDR(final String ip1, final String ip2, final long cidrSize) {
if (ip1 == null || ip1.isEmpty() || ip2 == null || ip2.isEmpty()) {
return true;
}
final String subnet1 = NetUtils.getCidrSubNet(ip1, cidrSize);
final String subnet2 = NetUtils.getCidrSubNet(ip2, cidrSize);
return subnet1.equals(subnet2);
}
public static String getSubNet(final String ip, final String netmask) {
final long ipAddr = ip2Long(ip);
final long subnet = ip2Long(netmask);
final long result = ipAddr & subnet;
return long2Ip(result);
}
public static String getCidrSubNet(final String ip, final long cidrSize) {
final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSize << MAX_CIDR - cidrSize;
final String netmask = NetUtils.long2Ip(numericNetmask);
return getSubNet(ip, netmask);
}
public static String ipAndNetMaskToCidr(final String ip, final String netmask) {
if (!isValidIp(ip)) {
return null;
}
if (!isValidNetmask(netmask)) {
return null;
}
final long ipAddr = ip2Long(ip);
final long subnet = ip2Long(netmask);
final long result = ipAddr & subnet;
int bits = subnet == 0 ? 0 : 1;
long subnet2 = subnet;
while ((subnet2 = subnet2 >> 1 & subnet) != 0) {
bits++;
}
return long2Ip(result) + "/" + Integer.toString(bits);
}
public static String[] ipAndNetMaskToRange(final String ip, final String netmask) {
final long ipAddr = ip2Long(ip);
long subnet = ip2Long(netmask);
final long start = (ipAddr & subnet) + 1;
long end = start;
int bits = subnet == 0 ? 0 : 1;
while ((subnet = subnet >> 1 & subnet) != 0) {
bits++;
}
end = end >> MAX_CIDR - bits;
end++;
end = (end << MAX_CIDR - bits) - 2;
return new String[] {long2Ip(start), long2Ip(end)};
}
public static Pair<String, Integer> getCidr(final String cidr) {
final String[] tokens = cidr.split("/");
return new Pair<String, Integer>(tokens[0], Integer.parseInt(tokens[1]));
}
public static enum SupersetOrSubset {
isSuperset, isSubset, neitherSubetNorSuperset, sameSubnet, errorInCidrFormat
}
public static SupersetOrSubset isNetowrkASubsetOrSupersetOfNetworkB(final String cidrA, final String cidrB) {
final Long[] cidrALong = cidrToLong(cidrA);
final Long[] cidrBLong = cidrToLong(cidrB);
long shift = 0;
if (cidrALong == null || cidrBLong == null) {
//implies error in the cidr format
return SupersetOrSubset.errorInCidrFormat;
}
if (cidrALong[1] >= cidrBLong[1]) {
shift = MAX_CIDR - cidrBLong[1];
} else {
shift = MAX_CIDR - cidrALong[1];
}
final long result = (cidrALong[0] >> shift) - (cidrBLong[0] >> shift);
if (result == 0) {
if (cidrALong[1] < cidrBLong[1]) {
//this implies cidrA is super set of cidrB
return SupersetOrSubset.isSuperset;
} else if (cidrALong[1].equals(cidrBLong[1])) {
//this implies both the cidrs are equal
return SupersetOrSubset.sameSubnet;
}
// implies cidrA is subset of cidrB
return SupersetOrSubset.isSubset;
}
//this implies no overlap.
return SupersetOrSubset.neitherSubetNorSuperset;
}
public static boolean isNetworkAWithinNetworkB(final String cidrA, final String cidrB) {
final Long[] cidrALong = cidrToLong(cidrA);
final Long[] cidrBLong = cidrToLong(cidrB);
if (cidrALong == null || cidrBLong == null) {
return false;
}
final long shift = MAX_CIDR - cidrBLong[1];
return cidrALong[0] >> shift == cidrBLong[0] >> shift;
}
public static Long[] cidrToLong(final String cidr) {
if (cidr == null || cidr.isEmpty()) {
return null;
}
final String[] cidrPair = cidr.split("\\/");
if (cidrPair.length != 2) {
return null;
}
final String cidrAddress = cidrPair[0];
final String cidrSize = cidrPair[1];
if (!isValidIp(cidrAddress)) {
return null;
}
int cidrSizeNum = -1;
try {
cidrSizeNum = Integer.parseInt(cidrSize);
} catch (final Exception e) {
return null;
}
final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSizeNum << MAX_CIDR - cidrSizeNum;
final long ipAddr = ip2Long(cidrAddress);
final Long[] cidrlong = {ipAddr & numericNetmask, (long)cidrSizeNum};
return cidrlong;
}
public static String getCidrSubNet(final String cidr) {
if (cidr == null || cidr.isEmpty()) {
return null;
}
final String[] cidrPair = cidr.split("\\/");
if (cidrPair.length != 2) {
return null;
}
final String cidrAddress = cidrPair[0];
final String cidrSize = cidrPair[1];
if (!isValidIp(cidrAddress)) {
return null;
}
int cidrSizeNum = -1;
try {
cidrSizeNum = Integer.parseInt(cidrSize);
} catch (final Exception e) {
return null;
}
final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSizeNum << MAX_CIDR - cidrSizeNum;
final String netmask = NetUtils.long2Ip(numericNetmask);
return getSubNet(cidrAddress, netmask);
}
public static String getCidrNetmask(final long cidrSize) {
final long numericNetmask = 0xffffffff >> MAX_CIDR - cidrSize << MAX_CIDR - cidrSize;
return long2Ip(numericNetmask);
}
public static String getCidrNetmask(final String cidr) {
final String[] cidrPair = cidr.split("\\/");
final long guestCidrSize = Long.parseLong(cidrPair[1]);
return getCidrNetmask(guestCidrSize);
}
public static String cidr2Netmask(final String cidr) {
final String[] tokens = cidr.split("\\/");
return getCidrNetmask(Integer.parseInt(tokens[1]));
}
public static long getCidrSize(final String netmask) {
final long ip = ip2Long(netmask);
int count = 0;
for (int i = 0; i < MAX_CIDR; i++) {
if ((ip >> i & 0x1) == 0) {
count++;
} else {
break;
}
}
return MAX_CIDR - count;
}
public static boolean isValidPort(final String p) {
try {
final int port = Integer.parseInt(p);
return !(port > 65535 || port < 1);
} catch (final NumberFormatException e) {
return false;
}
}
public static boolean isValidPort(final int p) {
return !(p > 65535 || p < 1);
}
public static boolean isValidLBPort(final String p) {
try {
final int port = Integer.parseInt(p);
return !(port > 65535 || port < 1);
} catch (final NumberFormatException e) {
return false;
}
}
public static boolean isValidProto(final String p) {
final String proto = p.toLowerCase();
return proto.equals(TCP_PROTO) || proto.equals(UDP_PROTO) || proto.equals(ICMP_PROTO);
}
public static boolean isValidSecurityGroupProto(final String p) {
final String proto = p.toLowerCase();
return proto.equals(TCP_PROTO) || proto.equals(UDP_PROTO) || proto.equals(ICMP_PROTO) || proto.equals(ALL_PROTO);
}
public static boolean isValidAlgorithm(final String p) {
final String algo = p.toLowerCase();
return algo.equals("roundrobin") || algo.equals("leastconn") || algo.equals("source");
}
public static boolean isValidAutoScaleAction(final String p) {
final String action = p.toLowerCase();
return action.equals("scaleup") || action.equals("scaledown");
}
public static String getLinkLocalNetMask() {
return "255.255.0.0";
}
public static String getLinkLocalGateway() {
return "169.254.0.1";
}