题解 | #验证IP地址#
验证IP地址
https://www.nowcoder.com/practice/55fb3c68d08d46119f76ae2df7566880
#include<stdio.h> #include<stdlib.h> #include<assert.h> int ipv4_is(char* src) { int i = 0, start = 0, node_count = 0, sum = 0; if(src[0] == '0') // 1.ipv4首个字母不为0 return -1; while(src[i] != '\0') { if(src[i] == '.' || src[i + 1] == '\0') { if(src[i - 1] == '.' || src[i + 1] == '0') // 判断是否连着出现..或者.0的情况 return -2; if(sum > 255 || node_count >= 3 || i - start > 3) // 判断数据是否在1-255之间 return -3; node_count++; // 统计遇到的‘.’的数量 sum = 0; i++; start = i; // 初始位置 } if(src[i] < '0' && src[i] > '9') // ipv4 只包含数字跟'.',否则非法 return -4; sum = sum * 10 + src[i] - '0'; // 在遇到‘.’之前,计算数值 i++; } return 0; } int ipv6_is(char* src) { int i = 0, j = 0, count = 0; while(src[i] != '\0') { if(src[i] == ':') { if(i - j > 4 || i == 0 || count == 8) // 判断一组16进制数是否超过4位,是否超过8组 return -1; else { i++; j = i; count++; // 计算遇到的 ‘:’数量 } } if( !((src[i] >= '0' && src[i] <= '9') || (src[i] >= 'a' && src[i] <= 'f') || (src[i] >= 'A' && src[i] <= 'F'))) // 排除除了数字和a-f,A-F之间的数 return -2; i++; } return 0; } char* solve(char* IP ) { assert(IP != NULL); int i = 0, flag; int len = strlen(IP); while(IP[i]!= '\0') { if(IP[i] == '.') { if(len < 7 || len > 15) return "Neither"; else { flag = ipv4_is(IP); if(flag == 0) return "IPv4"; else return "Neither"; } } if(IP[i] == ':') { if(len < 15 || len > 39) return "Neither"; else { flag = ipv6_is(IP); if(flag == 0) return "IPv6"; else return "Neither"; } } i++; } return "ok"; }