#include <stdio.h>
typedef char bool;
#define true 1
#define false 0
/**
1.判断字符串是否形如“192.168.1.1”
2.字符串两端含有空格视为合法ip,形如“ 192.168.1.1 ”
3.字符串中间含有空格视为非法ip,形如“192.168. 1.2”
4.字符串0开头视为不合法ip,形如192.168.01.1
5.字符串0.0.0.0视为合法ip
*/
bool checkIpv4(const char *ip){
printf("检验对象是:%s\n", ip);
if(NULL == ip) {
return false;
}
const char *q = ip; //字串指针
unsigned short int s = 0, count = 0, digitNumber = 0; //s是字串转化为的整型,count是 . 的个数, digitNumber 是 . 之间的数量
bool hasZero = false;
// 开头有空格
while(' ' == *q) {
q++;
}
while('\0' != *q) {
if('.' == *q) {
// . 前面没有任何值,则非法
if(digitNumber == 0) {
return false;
}
s = 0;
digitNumber = 0;
count++;
hasZero = false;
q++;
continue;
}
// 值非法
if(*q < '0' || *q > '9') {
// 结尾空格
if(' ' == *q && 3 == count) {
const char *qq = q;
while(' ' == *qq) {
qq++;
}
return '\0' == *qq;
} else{
return false;
}
}
int x = *q - '0';
s = s*10 + x;
// 0.0.0.0 合法, 00.0.0.0 不合法
if(0 == s) {
if(hasZero) {
return false;
} else{
hasZero = true;
}
}
if(s > 255) {
return false;
}
digitNumber++;
q++;
}
return (3 == count);
}
int main(void){
{
const int count = 10;
char *ip[count] = {"0.0.0.0", "255.255.255.255", "0.10.0.0", " 1.1.1.1", "1.1.1.1 ", " 1.1.1.1 "};
for(int i = 0; i < count; i++) {
if(checkIpv4(ip[i]))
printf("该地址是IPv4地址\n");
else
printf("该地址不是IPv4地址\n");
}
}
printf("\n\n");
{
const int count = 10;
char *ip[count] = {"1.1.1. 1", "1..2.3", "00.1.1.1", "a.1.1.1", };
for(int i = 0; i < count; i++) {
if(checkIpv4(ip[i]))
printf("该地址是IPv4地址\n");
else
printf("该地址不是IPv4地址\n");
}
}
return 0;
}