我们所知道的ip地址总共有五类,如下图所示:分别为A类、B类、C类、D类、E类

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
//计算ip地址一共有多少个.
int CountPoint(const char*str)
{
int count = 0;
while(*str != '\0')
{
if(*str == '.')
{
count++;
}
str++;
}
return count;
}
//IP地址的规则是: (1~255).(0~255).(0~255).(0~255)
bool IsCorrectIP( char* str)
{
assert(str != NULL);
int num = 0;
char tmp[4];
if(CountPoint(str) != 3)
{
return false;
}
if(str[0] == '0')
{
return false;
}
while(*str != '\0')
{
if(isdigit(*str))
{
//转换为十进制数字
num = num*10 + *str-'0';
}
//合法字段在0——255之间
else if(num < 0 || num > 255)
{
return false;
}
else if(*str != '.')
{
return false;
}
else
{
num = 0;
}
str++;
}
if(num > 255)
return false;
return true;
}
int main()
{
char *str = (char*)malloc(sizeof(char));
gets(str);
if(IsCorrectIP(str))
{
printf("%s 合法\n",str);
}
else
{
printf("%s不合法\n",str);
}
free(str);
return 0;
}
如果我们想把十进制的IP地址转换成二进制的可以参考如下代码~
//转换成二进制
void IP_B(int n)
{
int arr[8] = {0};
int i = 7,tmp,j;
while(n != 0)
{
tmp = n%2; //取余数再逆序
arr[i] = tmp;
n = n/2;
i--;
}
for(j = 0; j < 8; j++)
{
printf("%d",arr[j]);
}
}
本文介绍了一种IP地址验证方法,确保IP地址符合标准格式,并提供了一个将十进制IP地址转换为二进制格式的实用代码示例。
9280

被折叠的 条评论
为什么被折叠?



