写了个ipv4地址字符串转换为4个整型数的函数, 大佬们帮我看一下有没有啥问题, 跪谢
正确条件是: 仅包含数字, 空格, 点,
允许数字和点之间的空格,
点与点之间为空或为空格, 则默认为0, 如 '...' 视为'0.0.0.0',
点数量为3,
数值不大于255.
其他情况均为非法地址.
代码如下:
程序代码:
#include <stdio.h> #include <string.h> #include <ctype.h> int isIpv4Correct(const char*, int*); int main(int argc, char const *argv[]) { char ipv4str[50] = {}; int ipv4int[4] = {}; strcpy(ipv4str, "..."); puts(ipv4str); if (isIpv4Correct(ipv4str, ipv4int)) { puts("Correct!"); for (int i = 0; i < 4; i++) { printf("%d ", ipv4int[i]); } } else { puts("Error!"); } return 0; } int isIpv4Correct(const char *ipv4str, int *ipv4int) { int i = 0, ip = 0; int res = 0; int dotCount = 0; int inNum = 0; char cur = ipv4str[i]; while (cur) { if (!isdigit(cur) && cur != ' ' && cur != '.') { return 0; } else if (isdigit(cur)) { inNum = 1; res = res*10 + cur-'0'; if (res > 255) return 0; } else if (cur == ' ') { if (inNum) { return 0; } else { while (cur == ' ') { cur = ipv4str[++i]; } continue; } } else { ++dotCount; inNum = 0; ipv4int[ip++] = res; res = 0; } cur = ipv4str[++i]; } if (dotCount != 3) return 0; ipv4int[ip] = res; return 1; }