-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIPValidator.java
More file actions
51 lines (44 loc) · 1.13 KB
/
Copy pathIPValidator.java
File metadata and controls
51 lines (44 loc) · 1.13 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
package IPValidator;
public class IPValidator {
private static int index;
private static int dotIndex;
private static int intBufferValue;
private static int[] intBuffer;
public static boolean isIPValid(String IP) {
index = 0;
dotIndex = 0;
intBuffer = new int[3];
for (char currentChar : IP.toCharArray()) {
index += 1;
if (currentChar == '.') {
if (index == 4) {
// reached eos so checking if segment is valid
intBufferValue = intBuffer[0]*100+intBuffer[1]*10+intBuffer[2];
if (intBufferValue > 255 || intBufferValue < 0) {
// segment must be between 0 and 255
return false;
}
}
index = 0;
dotIndex += 1;
intBuffer = new int[3];
} else if (Character.isDigit(currentChar)) {
if (index == 4) {
// can't have more than 4 digits in a segment
return false;
} else {
// it is valid, add it to the buffer
intBuffer[index-1] = Character.getNumericValue(currentChar);
}
} else {
// letters can't be in IP's
return false;
}
}
if (dotIndex != 3) {
// IP must have 3 dots, no more or less
return false;
}
return true;
}
}