-
Notifications
You must be signed in to change notification settings - Fork 10
/
validate-ip-address.cpp
62 lines (58 loc) · 1.53 KB
/
validate-ip-address.cpp
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
// Time: O(1)
// Space: O(1)
class Solution {
public:
string validIPAddress(string IP) {
stringstream ss(IP);
string block;
if (IP.substr(0, 4).find('.') != string::npos) {
for (int i = 0; i < 4; ++i) {
if (!getline(ss, block, '.') || !isValidIPv4Block(block)) {
return "Neither";
}
}
if (ss.eof()) {
return "IPv4";
}
} else if (IP.substr(0, 5).find(':') != string::npos) {
for (int i = 0; i < 8; ++i) {
if (!getline(ss, block, ':') || !isValidIPv6Block(block)) {
return "Neither";
}
}
if (ss.eof()) {
return "IPv6";
}
}
return "Neither";
}
private:
bool isValidIPv4Block(const string& block) {
int num = 0;
if (block.size() > 0 && block.size() <= 3) {
for (int i = 0; i < block.size(); ++i) {
char c = block[i];
if (!isalnum(c) || (i == 0 && c == '0' && block.size() > 1)) {
return false;
} else {
num *= 10;
num += c - '0';
}
}
return num <= 255;
}
return false;
}
bool isValidIPv6Block(const string& block) {
if (block.size() > 0 && block.size() <= 4) {
for (int i = 0; i < block.size(); ++i) {
char c = block[i];
if (!isxdigit(c)) {
return false;
}
}
return true;
}
return false;
}
};