/** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * 验证IP地址 * @param IP string字符串 一个IP地址字符串 * @return string字符串 */ #include <ctype.h> #define isValid(ip) (ip >= 0 && ip <= 255) char* solve(char* IP ) { // write code here int i = 0; int ipv4 = 0; int ipv6 = 0; char temp[5]; int idx = 0; while(IP[i] != '.' && IP[i] != ':' && IP[i] != '\0') { temp[idx] = IP[i]; if(isalpha(IP[i])) ipv4 = -1; idx++; i++; } temp[idx] = '\0'; printf("temp is %s\n", temp); if(IP[i] == '.') { if(temp[0] == '0' && temp[1]) return "Neither"; int ip = atoi(temp); if(isValid(ip)) { ipv4++; i++; for(int j = ipv4; j < 4; j++) { idx = 0; while(IP[i] != '.' && IP[i] != '\0') { if(!isdigit(IP[i])) return "Neither"; temp[idx] = IP[i]; idx++; i++; } temp[idx] = '\0'; printf("temp is %s\n", temp); if(temp[0] == '0' && temp[1]) return "Neither"; if(idx == 0) return "Neither"; ip = atoi(temp); printf("atoi : %d\n", ip); if(isValid(ip)) { ipv4++; i++; } else { return "Neither"; } } } } else if(IP[i] == ':') { i = 0; for(int j = 0; j < 8; j++) { idx = 0; while(IP[i] != ':' && IP[i] != '\0') { if(idx <= 3 && isdigit(IP[i]) || (IP[i] >= 'A' && IP[i] <= 'F' || (IP[i] >= 'a' && IP[i] <= 'f'))) { temp[idx] = IP[i]; idx++; i++; } else { return "Neither"; } } temp[idx] = '\0'; if(idx == 0) return "Neither"; printf("%s\n", temp); i++; ipv6++; } } else { return "Neither"; } if(ipv4 == 4 && IP[i - 1] == '\0') return "IPv4"; else if(ipv6 == 8 && IP[i - 1] == '\0') return "IPv6"; return "Neither"; }