IP地址與無符號整數值相互轉換


方法1:
IP地址轉換為整數:比如"192.168.1.254",以點為分割,將192 168 1 254保存在一個int a[4]數組里,
然后通過unsigned int nResult = (a[3] << 24) + (a[2] << 16) + (a[1] << 8) + a[0]得到一個無符號32位整數。

整數轉換為IP地址:把這個整數轉換成一個無符號32位二進制數。從左到右,每八位進行一下分割,
得到4段8位的二進制數,把這些二進制數轉換成整數

#include <iostream>
#include <string>

using namespace std;

unsigned int IPToValue(const string& strIP)//IP轉換為整數
{
//IP轉化為數值
//沒有格式檢查
//返回值就是結果

int a[4];
string IP = strIP;
string strTemp;
size_t pos;
size_t i = 3;

do
{
pos = IP.find(".");

if (pos != string::npos)
{
strTemp = IP.substr(0, pos);
a[i] = atoi(strTemp.c_str());//int atoi(const char *str);
i--;
IP.erase(0, pos + 1);//從位置0開始刪除pos+1個字符
}
else
{
strTemp = IP;
a[i] = atoi(strTemp.c_str());
break;
}

} while (1);

unsigned int nResult = (a[3] << 24) + (a[2] << 16) + (a[1] << 8) + a[0];
return nResult;
}

string ValueToIP(const int& nValue)//整數轉換為ip
{
//數值轉化為IP
//沒有格式檢查
//返回值就是結果

char strTemp[20];
sprintf(strTemp, "%d.%d.%d.%d",
(nValue & 0xff000000) >> 24,
(nValue & 0x00ff0000) >> 16,
(nValue & 0x0000ff00) >> 8,
(nValue & 0x000000ff));

return string(strTemp);
}

int main()
{
string strIP = "192.168.1.254";
cout << IPToValue(strIP) << endl;

cout << ValueToIP(3232236030) << endl;

return 0;
}

方法2:使用win32 api
#include <iostream>
#include <winsock2.h>

#pragma comment(lib,"ws2_32.lib")
using namespace std;

int main(void)
{
cout << (unsigned int)htonl(inet_addr("192.168.1.254")) << endl;

struct in_addr addr;
addr.S_un.S_addr = ntohl(3232236030);
cout << inet_ntoa(addr) << endl;
return 0;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM