将整型ip转为点分十进制

通过将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;

测试结果如下:


说明可行

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值