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();
    }
發佈了31 篇原創文章 · 獲贊 1 · 訪問量 4萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章