写了个ip地址的分段提取的类,大家看看代码,给点建议
class Cip{
private:
int segment[4];
char *str;
int StrToInt(char *str);
bool CheckIp(char *str);
public:
int GetSeg(int sequence);
bool SetSeg(int sequence);
char GetIpType();
Cip(char *str_target);
~Cip();
};//solve an ipv4 address string
int Cip::GetSeg(int sequence)
{
if(sequence <= 4 && sequence >= 1)
return segment[sequence];
else
return -1;
}
bool Cip::CipCheckIp(char *str)
{
int dot_count = 0;
int num_count = 0;
while((*str))
{
if((*str) != '.')
{
if((*str) <= '9' && (*str) >= '0')
++ num_count;
else
return false;
}
else{
++ dot_count;
if(num_count < 1 || num_count > 4)//check if the current segment is 1~3 numbers
return false;
num_count = 0;//reset to 0
}
++ str;
}
if(dot_count != 3)
return false;
return true;
}
Cip::Cip(char *str_target)
{
int i = 0;
for(;i < 4;i++)
segment[i] = 0;
str = new char[15];//an ip string buffer
if(strlen(str_target) > 6 && strlen(str_target) < 16)//error check,x.x.x.x,min=6,max=15
strcpy(str,str_target);
else
strcpy(str,'\0');
}
Cip::~Cip()
{
delete[] str;
}
int Cip::StrToInt(char *str)
{
char *guard = str;
int cur_seg = 0;
int cur_quan = 0;
while((*guard) != '\0')
++ guard;
-- guard;
while(guard >= str)
{
if((*guard) != '.')
{
cur_int += ((*guard) - '0')*cur_quan*10;
++ cur_quan;
}
else{
segment[cur_seg] = cur_int;
cur_int = 0;//reset to 0
++ cur_seg;//segment index increase itself
cur_quan = 0;//reset to 0
}
-- guard;
}
}