unsigned long ip_string2int(const std::string& str_ip)
{
//IP转化为数值
//没有格式检查
//返回值就是结果
int a[4];
string ip = str_ip;
string strTemp;
size_t pos;
size_t i = 3;
do
{
pos = ip.find(".");
if (pos != string::npos)//string:npos表示未找到
{
strTemp = ip.substr(0, pos);
a[i] = atoi(strTemp.c_str());//string.c_str()将string转化为const char*,atoi函数将字符串转化为int,它的参数就是const char *,所以才要用c_str()转一下
i--;
ip.erase(0, pos + 1);
}
else
{
strTemp = ip;
a[i] = atoi(strTemp.c_str());
break;
}
} while (1);
for(i = 3; i >= 0;--i)
{
printf("a[%d] = %d\n", i, a[i]);
}
//这里你本来是期望执行4次的,但是因为i是size_t,而它是一个无符号类型的,所以会一直死循环下去。
return (a[3] << 24) + (a[2] << 16) + (a[1] << 8) + a[0];
}
inline std::string ip_int2string(unsigned int ip_value)
{
//数值转化为IP
std::stringstream str; //stringstream的用法看另一篇文章
str << ((ip_value & 0xff000000) >> 24) << “.”
<< ((ip_value & 0x00ff0000) >> 16) << “.”
<< ((ip_value & 0x0000ff00) >> 8) << “.”
<< (ip_value & 0x000000ff);
return str.str();
}