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();
}