ip地址与int类型的转换

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();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值