IP地址与无符号整数值相互转换
方法1:
IP地址轉(zhuǎn)換為整數(shù):比如"192.168.1.254",以點(diǎn)為分割,將192 168 1 254保存在一個(gè)int a[4]數(shù)組里,
然后通過(guò)unsigned int nResult = (a[3] << 24) + (a[2] << 16) + (a[1] << 8) + a[0]得到一個(gè)無(wú)符號(hào)32位整數(shù)。
整數(shù)轉(zhuǎn)換為IP地址:把這個(gè)整數(shù)轉(zhuǎn)換成一個(gè)無(wú)符號(hào)32位二進(jìn)制數(shù)。從左到右,每八位進(jìn)行一下分割,
得到4段8位的二進(jìn)制數(shù),把這些二進(jìn)制數(shù)轉(zhuǎn)換成整數(shù)
#include <iostream>
#include <string>
using namespace std;
unsigned int IPToValue(const string& strIP)//IP轉(zhuǎn)換為整數(shù)
{
//IP轉(zhuǎn)化為數(shù)值
//沒有格式檢查
//返回值就是結(jié)果
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個(gè)字符
}
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)//整數(shù)轉(zhuǎn)換為ip
{
//數(shù)值轉(zhuǎn)化為IP
//沒有格式檢查
//返回值就是結(jié)果
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;
總結(jié)
以上是生活随笔為你收集整理的IP地址与无符号整数值相互转换的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: (二)流--递归算法
- 下一篇: 分享一个好用的函数吧,将js中的对象转成