用C++输入一串字符串,判断是否为合法的IP地址,如果是,指出是哪一类IP地址
展开全部
#include<stdio.h>
#include<string.h>
int isip(char*str,int* f)
{
int bip[4] = { 999, 999, 999, 999 };
char cp[3] = { 0 };
char o = 0;
int i;
if (sscanf(str, "%d%c%d%c%d%c%d%c", bip, cp, bip + 1, cp + 1, bip + 2, cp + 2, bip + 3, &o) != 7) return 0;
for (i = 0; i < 4; i++)
if (bip[i] < 0 || bip[i]>255) return 0;
for (i = 0; i < 3; i++)
if (cp[i] != '.') return 0;
*f = 0;
if (1 <= *bip&&*bip <= 126)
*f =2;
else if (127 == *bip)
*f = 1;
else if (128 <= *bip&&*bip <= 191)
*f = 3;
else if (192 <= *bip&&*bip <= 223)
*f = 4;
else if (224 <= *bip&&*bip <= 239)
*f = 5;
else if (240 <= *bip&&*bip <= 255)
*f = 6;
return 1;
}
char* rtrim(char* str)
{
int len = strlen(str);
while (str[len - 1] == ' ')
{
str[len - 1] = 0;
--len;
}
return str;
}
int main()
{
char str[100];
int f=0;
char* iptype[7] = { "不是ip地址", "私有保留地址", "A类地址", "B类地址", "C类地址", "D类地址", "E类地址" };
char* r[2] = { "不是", "是" };
scanf("%s",str);
printf("%s\n%s\n", r[isip(rtrim(str), &f)], iptype[f]);
return 0;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询