C编程:字符串型IP地址转换为无符号整型


main.cpp

#include <stdio.h>
#include <stdlib.h>


enum CHAR_TYPE {
CHAR_TYPE_INIT = 0,
CHAR_TYPE_DIGIT,
CHAR_TYPE_DOT,
CHAR_TYPE_SPACE
};


int convert_ip(const char *src_ip, unsigned int* dst_ip){

if((src_ip == NULL) || (dst_ip == NULL))
{
 return -1;
}


int curr_section_num = 0;
unsigned int total_number = 0;


enum CHAR_TYPE previous_no_space_type = CHAR_TYPE_INIT;
enum CHAR_TYPE last_char_type = CHAR_TYPE_INIT;
int dot_count = 0;


for(int i=0; src_ip[i] != '\0'; i++)
{
if((src_ip[i] >= '0') && (src_ip[i] <= '9'))
{
if((last_char_type == CHAR_TYPE_SPACE) && (previous_no_space_type == CHAR_TYPE_DIGIT))
{
return -1;
}


curr_section_num = curr_section_num*10 + (int(src_ip[i])-int('0'));
if (curr_section_num > 255)
{
return -1;
}


last_char_type = CHAR_TYPE_DIGIT;
previous_no_space_type = CHAR_TYPE_DIGIT;


}
else if(src_ip[i] == '.')
{
if((last_char_type == CHAR_TYPE_SPACE) && (previous_no_space_type == CHAR_TYPE_DOT))
{
return -1;
}

if(dot_count++ > 3 )
{
return -1;
}


total_number = total_number*256 + curr_section_num;
curr_section_num = 0;


last_char_type = CHAR_TYPE_DOT;
previous_no_space_type = CHAR_TYPE_DOT;


}
else
{
last_char_type = CHAR_TYPE_SPACE;


}
}


total_number = total_number*256 + curr_section_num;
*dst_ip = total_number;


return 0;
}


void unittest1(){
char *src_ip = "172.168.5.1";
unsigned int dst_ip = 0;
if(convert_ip(src_ip, &dst_ip) == -1)
printf ("%s invalid\n", src_ip);
else
printf ("%s => %u\n", src_ip, dst_ip);
}


void unittest2(){
char *src_ip = "172 . 168.5.1";
unsigned int dst_ip = 0;
if(convert_ip(src_ip, &dst_ip) == -1)
printf ("%s invalid\n", src_ip);
else
printf ("%s => %u\n", src_ip, dst_ip);
}


void unittest3(){
char *src_ip = "172   .    168.5.1";
unsigned int dst_ip = 0;
if(convert_ip(src_ip, &dst_ip) == -1)
printf ("%s invalid\n", src_ip);
else
printf ("%s => %u\n", src_ip, dst_ip);
}


void unittest4(){
char *src_ip = "1 72.168.5.1";
unsigned int dst_ip = 0;
if(convert_ip(src_ip, &dst_ip) == -1)
printf ("%s invalid\n", src_ip);
else
printf ("%s => %u\n", src_ip, dst_ip);
}


void unittest5(){
char *src_ip = "1   72.168.5.1";
unsigned int dst_ip = 0;
if(convert_ip(src_ip, &dst_ip) == -1)
printf ("%s invalid\n", src_ip);
else
printf ("%s => %u\n", src_ip, dst_ip);
}


void unittest6(){
char *src_ip = "172. .5.1";
unsigned int dst_ip = 0;
if(convert_ip(src_ip, &dst_ip) == -1)
printf ("%s invalid\n", src_ip);
else
printf ("%s => %u\n", src_ip, dst_ip);
}




int main(int argc, char **argv) {
unittest1();
unittest2();
unittest3();
unittest4();
unittest5();
unittest6();


}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值