ip地址转换: char * <---> unsigned int

       仅做记录:

 

#include<iostream>
#include<sys/socket.h>
#include<netinet/in.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;

int main()
{
	char szIP[32] = "10.172.18.18";
	unsigned int ulIP1 = htonl(inet_addr(szIP));
	cout << ulIP1 << endl;

	unsigned int ulIP2 = htonl(ulIP1);
	string resultIP=inet_ntoa(*(in_addr*)(&ulIP2));
	cout << resultIP << endl;

	return 0;
}

     结果:

 

179048978
10.172.18.18

 

     有时候如果忘了大小端字节序, 就容易出错, 如转成了18.18.172.10.

 

     再来看下:

 

#include    <iostream>
#include    <string>
using namespace std;

string uiIP2Str(unsigned int uiIP, bool bNetByteOrder = true)
{
    char szIP[16] = {0};
    unsigned char *c = (unsigned char *)&uiIP;
    if(bNetByteOrder)
    {
        snprintf(szIP, sizeof(szIP), "%hhu.%hhu.%hhu.%hhu", *c, *(c+1), *(c+2), *(c+3));
    }
    else
    {
        snprintf(szIP, sizeof(szIP), "%hhu.%hhu.%hhu.%hhu", *(c+3), *(c+2), *(c+1), *c);
    }
	
    return string(szIP);
}

int main()
{
	unsigned int uiIP = 179048978;
	cout << uiIP2Str(uiIP, false) << endl;

    return 0;
}

       结果:10.172.18.18
 

 

 

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值