我們所知道的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]);
}
}