#include <iostream> #include <algorithm> using namespace std; class Solution { public: string validIPAddress(string IP) { //以.和:来区分ipv4和ipv6 for (int i = 0; i < IP.length(); i++) { if (IP[i] == '.') return isIPv4(IP) ? "IPv4" : "Neither"; else if (IP[i] == ':') return isIPv6(IP) ? "IPv6" : "Neither"; } return "Neither"; } private: bool isIPv4(string IP) { int dotcnt = 0; //数一共有几个. for (int i = 0; i < IP.length(); i++) { if (IP[i] == '.') dotcnt++; } //ipv4地址一定有3个点 if (dotcnt != 3) return false; string temp = ""; for (int i = 0; i < IP.length(); i++) { if (IP[i] != '.') temp += IP[i]; //被.分割的每部分一定是数字0-255的数字 if (IP[i] == '.' || i == IP.length() - 1) { if (temp.length() == 0 || temp.length() > 3) return false; for (int j = 0; j < temp.length(); j++) { if (!isdigit(temp[j])) return false; } int tempInt = stoi(temp); if (tempInt > 255 || tempInt < 0) return false; string convertString = to_string(tempInt); if (convertString != temp) return false; temp = ""; } } if (IP[IP.length()-1] == '.') return false; return true; } bool isIPv6(string IP) { int dotcnt = 0; for (int i = 0; i < IP.length(); i++) { if(IP[i] == ':') dotcnt++; } if (dotcnt != 7) return false; string temp = ""; for (int i = 0; i < IP.length(); i++) { if (IP[i] != ':') temp += IP[i]; if (IP[i] == ':' || i == IP.length() - 1) { if (temp.length() == 0 || temp.length() > 4) return false; for (int j = 0; j < temp.length(); j++) { if (!(isdigit(temp[j]) ||(temp[j] >= 'a' && temp[j] <= 'f') || (temp[j] >= 'A' && temp[j] <= 'F'))) return false; } temp = ""; } } if (IP[IP.length()-1] == ':') return false; return true; } }; int main() { Solution sol; string s; while(1){ cout << "Please input a string: " << endl; cin >> s; if(s == "exit"){ break; } cout << sol.validIPAddress(s) << endl; } cout << "bye" << endl; return 0; } 运行结果:
举报
本版积分规则 发表回复 回帖并转播 回帖后跳转到最后一页
等级类勋章
发帖类勋章
时间类勋章
人才类勋章
1478
12917
55
扫码关注 21ic 官方微信
扫码关注嵌入式微处理器
扫码关注电源系统设计
扫码关注21ic项目外包
扫码浏览21ic手机版
本站介绍 | 申请友情链接 | 欢迎投稿 | 隐私声明 | 广告业务 | 网站地图 | 联系我们 | 诚聘英才
京公网安备 11010802024343号