01: package org.bouncycastle.util;
02:
03: import java.math.BigInteger;
04:
05: public class IPAddress {
06: private static final BigInteger ZERO = BigInteger.valueOf(0);
07:
08: /**
09: * Validate the given IPv4 or IPv6 address.
10: *
11: * @param address the IP address as a String.
12: *
13: * @return true if a valid address, false otherwise
14: */
15: public static boolean isValid(String address) {
16: return isValidIPv4(address) || isValidIPv6(address);
17: }
18:
19: /**
20: * Validate the given IPv4 address.
21: *
22: * @param address the IP address as a String.
23: *
24: * @return true if a valid IPv4 address, false otherwise
25: */
26: private static boolean isValidIPv4(String address) {
27: if (address.length() == 0) {
28: return false;
29: }
30:
31: BigInteger octet;
32: int octets = 0;
33:
34: String temp = address + ".";
35:
36: int pos;
37: int start = 0;
38: while (start < temp.length()
39: && (pos = temp.indexOf('.', start)) > start) {
40: if (octets == 4) {
41: return false;
42: }
43: try {
44: octet = (new BigInteger(temp.substring(start, pos)));
45: } catch (NumberFormatException ex) {
46: return false;
47: }
48: if (octet.compareTo(ZERO) == -1
49: || octet.compareTo(BigInteger.valueOf(255)) == 1) {
50: return false;
51: }
52: start = pos + 1;
53: octets++;
54: }
55:
56: return octets == 4;
57: }
58:
59: /**
60: * Validate the given IPv6 address.
61: *
62: * @param address the IP address as a String.
63: *
64: * @return true if a valid IPv4 address, false otherwise
65: */
66: private static boolean isValidIPv6(String address) {
67: if (address.length() == 0) {
68: return false;
69: }
70:
71: BigInteger octet;
72: int octets = 0;
73:
74: String temp = address + ":";
75:
76: int pos;
77: int start = 0;
78: while (start < temp.length()
79: && (pos = temp.indexOf(':', start)) > start) {
80: if (octets == 8) {
81: return false;
82: }
83: try {
84: octet = (new BigInteger(temp.substring(start, pos), 16));
85: } catch (NumberFormatException ex) {
86: return false;
87: }
88: if (octet.compareTo(ZERO) == -1
89: || octet.compareTo(BigInteger.valueOf(0xFFFF)) == 1) {
90: return false;
91: }
92: start = pos + 1;
93: octets++;
94: }
95:
96: return octets == 8;
97: }
98: }
|