通过将ip地址以整型16进制打出来,可以得到一些信息,比如192.168.251.10在内存中16进制为C0A8FB0A,它的Uint32是-1062667510;可以采用移位等方式将整型ip转换为点分十进制字串
具体实现程序如下:
/*
* main.cpp
*
* Created on: 2017年8月21日
* Author:
*/
#include <iostream>
#include <stdio.h>
#include <sstream>
#include <cstring>
#include <cstdlib>
#include "baseTypeDef.h"
using namespace std;
namespace Csl
{
std::string itoa(Int32 num)
{
std::stringstream strm;
std::string numstr;
strm << num;
numstr = strm.str();
return numstr;
}
/* 这里的ip是主机序,如果是网络序,需要转换为主机序 */
char *num2Ip1(Uint32 clientIp)
{
char* buf = new char[sizeof("aaa.bbb.ccc.ddd")];
unsigned char* p = (unsigned char *)&clientIp;
sprintf(buf, "%d.%d.%d.%d", p[3]&0xff,p[2]&0xff,p[1]&0xff,p[0]&0xff);
return buf;
}
std::string num2Ip2(Uint32 clientIp)
{
std::string ip;
std::stringstream strm;
for (int i = 3; i >= 0; i--)
{
strm << itoa((clientIp>>8*i)&0xff);
if (i != 0)
{
strm << ".";
}
}
ip = strm.str();
return ip;
}
};
int main()
{
Uint32 clientIp = -1062667510;
cout << "clientIp:" << Csl::num2Ip1(clientIp) << endl;
cout << "clientIp2:" << Csl::num2Ip2(clientIp) << endl;
return 0;
}
还可以采用linux下的系统调用inet_ntop还得到ip字串
struct in_addr addr;
addr.s_addr = htonl(3232260379);
void *tmpPtr = NULL;
tmpPtr = &addr;
char buf[1024];
inet_ntop (AF_INET, tmpPtr, buf, sizeof (buf));
cout << buf << endl;
测试结果如下:
说明可行