日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

IP地址与无符号整数值相互转换

發(fā)布時(shí)間:2023/12/15 编程问答 28 豆豆
生活随笔 收集整理的這篇文章主要介紹了 IP地址与无符号整数值相互转换 小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

方法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)題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。