将字符串IP地址解析成数组IP

uint8_t  StrToIP(const int8_t* str, void *ip)
{
	    /* The count of the number of bytes processed. */
	    int i;

	    /* A pointer to the next digit to process. */
	    const char * start;

	    start = str;	// 字符串指针赋值

	    // IPV4
	    //---------------------------------------------------
	    for (i = 0; i < 4; i++)		// 一共四个十进制字符串
	    {
	        /* The digit being processed. */
	        char c;
	        /* The value of this byte. */
	        int n = 0;

	        while (1)
	        {
	            c = * start;	// 字符串某字符赋值

	            start++;		// 从前往后(从左向右)

	            if (c >= '0' && c <= '9')	// 在“0~9”范围内
	            {
	                n *= 10;		// 权重
	                n += c - '0';	// 将'0'~'9'字符转换为对应的数字
	            }

	            /* We insist on stopping at "." if we are still parsing
	               the first, second, or third numbers. If we have reached
	               the end of the numbers, we will allow any character. */
	            else if ((i < 3 && c == '.') || i == 3)
	            {
	                break;		// 遇到'.'则解析下一十进制字符串
	            }

	            else
	            {
	                return 0;	// 解析失败
	            }
	        }

	        if (n >= 256)	// n过大,解析失败
	        {
	            return 0;
	        }

	        ((uint8_t*)ip)[i] = n;	// 赋值给IP数组
	    }

	    return 1;	// 解析成功,返回1
}

 

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值