yongde1990的gravatar头像
yongde1990 2018-03-21 22:00:55
c语言实现IP地址转换为16进制输出

输入 : 1.168.229.200 
输出 :0x01 0xa8 0xe5 0xc8

#include <arpa/inet.h>
#include <netinet/in.h>
#include <iomanip>
#include <bitset>
#include <sstream>
#include<stdio.h>
#include<stdlib.h>

string ip_to_hex_str(const string& ip)
{
    char* ch_ip = const_cast<char*>(ip.c_str());
    struct in_addr ia_ip;

    char hex_ip[8]={0};
    unsigned long long_ip;
    long_ip=inet_addr(ch_ip);
    for(int i=0; i < 4;i++)
    {
        sprintf(hex_ip+(i*2),"%02x",*((unsigned char*)(&long_ip)+i));
    }


    ostringstream ost_des;
    ost_des << "0x" << hex_ip[0] << hex_ip[1] << " 0x" << hex_ip[2] << hex_ip[3]
    << " 0x" << hex_ip[4] << hex_ip[5] << " 0x" << hex_ip[6] << hex_ip[7];
    return ost_des.str();
}

int main(int argc, char ** argv)
{
    string str1 = "1.168.229.200";
    cout<< ip_to_hex_str(str1) << endl;
    return 0;
}

打赏
最近浏览
uncledrew01 2021年4月12日
暂无贡献等级
1546111923  LV3 2020年10月16日
最代码官方  LV168 2018年3月21日
顶部 客服 微信二维码 底部
>扫描二维码关注最代码为好友扫描二维码关注最代码为好友