经常找类似的函数,但是总是不尽如人意。
自己写个供大家参考吧,省的到处搜,浪费时间
原理很简单就是根据点分十进制的样式进行比对,一个字符一个字符的匹配,存在三个点,且字符为数字,并且值小于等于255,大于等于0.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int is_valid_ip(const char *str) {
char tmp[32];
memset(tmp, 0, sizeof(tmp));
strcpy(tmp, str);
if (strlen(tmp) < 7 || strlen(tmp) > 15)
{
return 0;
}
char *p = tmp, *start = tmp;
int a= 0;
p = strchr(p, '.');
if (p == NULL) return 0;
*p = '\0';
a = atoi(start);
while(*start) {
if (!isdigit(*start))return 0;
start++;
}
//printf("a=%d, [p=%s]\n", a, p);
if (a < 0 ||a > 255) return 0;
p++;
start = p;
p = strchr(p, '.');
if (p == NULL) return 0;
*p = '\0';
a = atoi(start);
while(*start) {
if (!isdigit(*start))return 0;
start++;
}
//printf("a=%d, [p=%s]\n", a, p);
if (a < 0 ||a > 255) return 0;
p++;
start = p;
p = strchr(p, '.');
if (p == NULL) return 0;
*p = '\0';
a = atoi(start);
while(*start) {
if (!isdigit(*start))return 0;
start++;
}
//printf("a=%d, [p=%s]\n", a, p);
if (a < 0 || a > 255) return 0;
p++;
start = p;
if (strchr(p, '.')) { //192.168.1..1
printf("Too many dot\n");
return 0;
}
int len = strlen(p); //192.168.1.
if (len == 0 || len > 3) return 0;
a = atoi(start);
while(*p) {
if (!isdigit(*p))return 0;
p++;
}
//printf("a=%d, [p=%s]\n", a, p);
if (a < 0 || a > 255) return 0;
return 1; // 是合法的IP地址
}
int main(int argc, char *argv[]) {
char ip[] = "192.168.1.x";
printf("%s is%s a valid IP address.\n", argv[1], is_valid_ip(argv[1]) ? "" : " not");
return 0;
}