`
mylove2060
  • 浏览: 330790 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Boost - C++的转化数字IP到字符串IP

阅读更多
*    INET_ATON(expr)

给出一个作为字符串的网络地址的"点地址"(如127.0.0.1)表示,返回一个代表该地址数值的整数。地址可以是4或8比特地址。

mysql> SELECT INET_ATON('209.207.224.40');

        -> 3520061480

产生的数字总是按照网络字节顺序。如上面的例子,数字按照 209×2563 + 207×2562 + 224×256 + 40 进行计算。

INET_ATON() 也能理解短格式 IP 地址:

mysql> SELECT INET_ATON('127.0.0.1'), INET_ATON('127.1');

        -> 2130706433, 2130706433

注释: 在存储由INET_ATON() 产生的值时,推荐你使用 INT UNSIGNED 列。假如你使用 (带符号) INT列, 则相应的第一个八位组大于127的IP 地址值会被截至  2147483647 (即, INET_ATON('127.255.255.255') 所返回的值)。请参见11.2节,“数值类型”。

    * INET_NTOA(expr)

给定一个数字网络地址 (4 或 8 比特),返回作为字符串的该地址的电地址表示。
   *   
mysql> SELECT INET_NTOA(3520061480);

        -> '209.207.224.40'

以上文章转载,现在的项目就是从数据库里取到一个IP数字,转化成实际的IP
在网上找了很久没有现成的,后来还是自己写了个方法,也很简单。


Author:QQ174554431


// TestBoostLibrary.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <string>
#include <vector>
#include <iostream>

#include <boost/cstdint.hpp> 
#include <boost/lexical_cast.hpp>
#include <sstream> 
void ConvertNumberIpAddress(boost::uint32_t &in_ipNumberAddress,std::string &out_validIpAddress)
{
	if(in_ipNumberAddress<0||in_ipNumberAddress>4294967295)
	{
		out_validIpAddress = "0.0.0.0"; //invalid IP Address
	}
	else
	{
		boost::uint32_t divisor = 256; 
		boost::uint32_t ip_section1 = 0;
		boost::uint32_t ip_section2 = 0;
		boost::uint32_t ip_section3 = 0;
		boost::uint32_t ip_section4 = 0;

		std::string ip_section_str1;
		std::string ip_section_str2;
		std::string ip_section_str3;
		std::string ip_section_str4;
		std::string dot = ".";

		ip_section1 = in_ipNumberAddress%divisor;
		in_ipNumberAddress = in_ipNumberAddress/divisor;
		ip_section2 = in_ipNumberAddress%divisor;
		in_ipNumberAddress = in_ipNumberAddress/divisor;
		ip_section3 = in_ipNumberAddress%divisor;
		in_ipNumberAddress = in_ipNumberAddress/divisor;
		ip_section4 = in_ipNumberAddress%divisor;
		ip_section_str1 = boost::lexical_cast <std::string> (ip_section1);
		ip_section_str2 = boost::lexical_cast <std::string> (ip_section2);
		ip_section_str3 = boost::lexical_cast <std::string> (ip_section3);
		ip_section_str4 = boost::lexical_cast <std::string> (ip_section4);
		out_validIpAddress = ip_section_str4+dot+ip_section_str3+dot+ip_section_str2+dot+ip_section_str1;
	}
}
int _tmain(int argc, _TCHAR* argv[])
{
	boost::uint32_t subnet = 3520061480;
	std::string ipAddress;
	ConvertNumberIpAddress(subnet,ipAddress);
	std::cout<<ipAddress<<std::endl;
	return 0;
}




运行结果:209.207.224.40
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics