-
Notifications
You must be signed in to change notification settings - Fork 0
/
IPadrress.cpp
113 lines (56 loc) · 1.51 KB
/
IPadrress.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
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
#include<iostream>
using namespace std;
string validIPAddress6(string IP) {
int h = 0;
for(int i = 0; i < IP.length(); i++)
{
string r = "";
if(IP[0] == '0' ) return "Neither"; // first term is a leading zero
while(IP[i] != ':' && i < IP.length())
{
if(!isxdigit(IP[i])) return "Neither";
r += IP[i];
i++;
}
if(IP[i] == ':') h++;
if(r == "") return "Neither";
else if(r.length() > 4) return "Neither";
}
if( h != 7) return "Neither";
return "IPv6";
}
string validIPAddress4(string IP) {
int k = 0; // counter for number of decimal places
for(int i = 0; i < IP.length(); i++)
{
string t = "";
while(IP[i] != '.' && i < IP.length())
{
if(!isdigit(IP[i])) return "Neither";
t += IP[i];
i++;
}
if(IP[i] == '.') k++;
if(IP[IP.length() - 1] == '.') return "Neither";
else if(t.length() > 1 && t[0] == '0') return "Neither";
else if(t.length() > 3 || t == "") return "Neither";
else if( stod(t) > 255) return "Neither";
}
if( k != 3) return "Neither"; // format is not correct if there are not three dots
return "IPv4";
}
string validIPAddress(string IP){
int p = 0;
while(isalnum(IP[p]))
{
p++;
}
if( IP[p] == '.') return validIPAddress4(IP);
else if(IP[p] == ':') return validIPAddress6(IP);
return "Neither";
}
int main(){
string test = "1.0.1.";
cout << validIPAddress4(test) << endl;
return 0;
}