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'
[color=blue]
以上文章转载,现在的项目就是从数据库里取到一个IP数字,转化成实际的IP
在网上找了很久没有现成的,后来还是自己写了个方法,也很简单。[/color]
[color=green][i][b]
Author:QQ174554431
[/b][/i][/color]


// 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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值