写了个ip地址的分段提取的类,大家看看代码,给点建议

tarsen tarsen 墨衍会员 · AI 创作全网分发 墨衍智能分发 通过墨衍一键同步至各平台 可同步平台 CSDN微信公众号微博知乎掘金百家号博客园抖音小红书 你的文章也可以这样分发 墨衍会员 ¥399起/年,写一次发全网 我也要 + 加入社区
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;
}
}
...全文

相关推荐

评论 26
收藏 已收藏
分享
返回顶部
tarsen
C++ 语言 65,214 成员 250,514 内容