仅做记录:
#include<iostream>
#include<sys/socket.h>
#include<netinet/in.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main()
{
char szIP[32] = "10.172.18.18";
unsigned int ulIP1 = htonl(inet_addr(szIP));
cout << ulIP1 << endl;
unsigned int ulIP2 = htonl(ulIP1);
string resultIP=inet_ntoa(*(in_addr*)(&ulIP2));
cout << resultIP << endl;
return 0;
}
结果:
179048978
10.172.18.18
有时候如果忘了大小端字节序, 就容易出错, 如转成了18.18.172.10.
再来看下:
#include <iostream>
#include <string>
using namespace std;
string uiIP2Str(unsigned int uiIP, bool bNetByteOrder = true)
{
char szIP[16] = {0};
unsigned char *c = (unsigned char *)&uiIP;
if(bNetByteOrder)
{
snprintf(szIP, sizeof(szIP), "%hhu.%hhu.%hhu.%hhu", *c, *(c+1), *(c+2), *(c+3));
}
else
{
snprintf(szIP, sizeof(szIP), "%hhu.%hhu.%hhu.%hhu", *(c+3), *(c+2), *(c+1), *c);
}
return string(szIP);
}
int main()
{
unsigned int uiIP = 179048978;
cout << uiIP2Str(uiIP, false) << endl;
return 0;
}
结果:10.172.18.18