-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathIpValidator.java
More file actions
93 lines (80 loc) · 2.81 KB
/
Copy pathIpValidator.java
File metadata and controls
93 lines (80 loc) · 2.81 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
import java.util.Arrays;
public class IpValidator {
/**
* Validates an IP address of the form w.x.y.z:port
* - w, x, y, z must each be in range [0, 255] (one byte)
* - port must be in range [1, 65535] inclusive
*/
public static boolean isValidIpAddress(String input) {
if (input == null || input.isEmpty()) {
return false;
}
int port;
if (input.indexOf(":") != -1) {
try {
port = Integer.parseInt(input.split(":", -1)[1]);
} catch(NumberFormatException e) {
return false;
}
if (port < 1 || port > 65535) {
return false;
}
}
String[] parts = input.split(":")[0].split("\\.");
if (parts.length != 4) {
return false;
}
Integer[] intParts;
try {
intParts = Arrays.stream(parts).map(Integer::valueOf).toArray(Integer[]::new);
} catch(NumberFormatException e) {
return false;
}
for (int number : intParts) {
if (number < 0 || number > 255) {
return false;
}
}
return true;
}
public static void main(String[] args) {
// Test cases
String[] valid = {
"192.168.1.1:8080",
"0.0.0.0:1",
"255.255.255.255:65535",
"10.0.0.1:443",
};
String[] invalid = {
"256.0.0.1:80", // octet out of range
"192.168.1.1:0", // port 0 not allowed
"192.168.1.1:65536", // port too high
"192.168.1:80", // only 3 octets
"192.168.1.1.1:80", // 5 octets
"192.168.1.abc:80", // non-numeric octet
"192.168.1.1:", // empty port
":80", // missing IP
"", // empty string
};
String[] validNoPort = {
"192.168.1.1", // valid IP, no port
"0.0.0.0",
"255.255.255.255",
};
System.out.println("=== Should be TRUE ===");
for (String s : valid) {
boolean result = isValidIpAddress(s);
System.out.printf(" %-30s -> %s%n", s, result ? "PASS" : "FAIL (expected true)");
}
System.out.println("=== Should be FALSE ===");
for (String s : invalid) {
boolean result = isValidIpAddress(s);
System.out.printf(" %-30s -> %s%n", s, result ? "FAIL (expected false)" : "PASS");
}
System.out.println("=== Should be TRUE (no port) ===");
for (String s : validNoPort) {
boolean result = isValidIpAddress(s);
System.out.printf(" %-30s -> %s%n", s, result ? "PASS" : "FAIL (expected true)");
}
}
}