判断一个IP地址是否是合法

本文介绍了一种IP地址验证方法,确保IP地址符合标准格式,并提供了一个将十进制IP地址转换为二进制格式的实用代码示例。

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值