现在的位置: 首页 > 综合 > 正文

ACE ipv4地址转换示例

2013年08月06日 ⁄ 综合 ⁄ 共 545字 ⁄ 字号 评论关闭
#include "ace/OS.h"
#include <iostream>
#include <string>

//主机字节序int转换为ipv4字符串地址
inline 
std::string int2ip(unsigned long ip)
{
	char buf[20];
	ip = htonl(ip);
	return ACE_OS::inet_ntop(AF_INET, &ip, buf, 20);
}

// ipv4字符串地址转换为主机字节序int
inline 
unsigned long ip2int(const char* ip) 
{
	unsigned long tmp;
	//ipv4地址
	ACE_OS::inet_pton(AF_INET, ip, &tmp);
	return ntohl(tmp);
}

int ACE_TMAIN(int, ACE_TCHAR *[])
{
	const char* ip = "192.16.1.100";
	unsigned long nIp = ip2int(ip);

	printf("0x%x\n", nIp);

	std::string strIp = int2ip(nIp);
	printf("%s\n", strIp.c_str());

	return 0;
};

输出结果:

0xc0100164
192.16.1.100
Press any key to continue

抱歉!评论已关闭.