linux网络-点分十进制和网络字节序转换

基本概念

#include <arpa/inet.h>
in_addr_t inet_addr(const char *string);

该函数的作用是将用点分十进制字符串格式表示的IP地址转换成32位大端序整型。

成功时返回32位大端序整型数值,失败时返回 INADDR_NONE 。

代码

#include <stdio.h>
#include <arpa/inet.h>

int main( void ){

    const char* ip1 = "1.2.3.4";
    const char* ip2 = "192.168.1.1";

    in_addr_t data;

    data = inet_addr( ip1 );
    printf( "%s -> %#x\n", ip1, data );

    data = inet_addr( ip2 );
    printf( "%s -> %#x\n", ip2, data );

    return 0;
}
/*
1.2.3.4 -> 0x4030201
192.168.1.1 -> 0x101a8c0
*/

基本概念

char * inet_ntoa(struct in_addr addr);

该函数的作用与 inet_addr 正好相反。将32位大端序整型格式IP地址转换为点分十进制格式。

成功时返回转换的字符串地址值,失败时返回-1。

代码

#include <stdio.h>
#include <arpa/inet.h>

int main( void ){

    struct in_addr addr1;
    struct in_addr addr2;

    char* s1 = NULL;
    char* s2 = NULL;

    unsigned long host1 = 0x01020304;
    unsigned long host2 = 0xc0a80101;
    addr1.s_addr = htonl(host1);
    addr2.s_addr = htonl(host2);

    s1 = inet_ntoa(addr1);
    s2 = inet_ntoa(addr2);

    printf( "%#x -> %s.\n", addr1.s_addr, s1 );
    printf( "%#x -> %s.\n", addr2.s_addr, s2 );


    return 0;
}
/*
0x4030201 -> 192.168.1.1.
0x101a8c0 -> 192.168.1.1.
*/

出现以上的错误是因为,这个函数的结果存放在statically allocated buffer。然后返回这个地址。
如果不及时将数据拷贝走,下次会覆盖,所以上面的代码输出的是最后一次的结果。

可修改如下:

#include <stdio.h>
#include <arpa/inet.h>
#include <string.h>
#define BUF_SZ 32

int main( void ){

    struct in_addr addr1;
    struct in_addr addr2;

    char* s = NULL;
    char buf1[BUF_SZ];
    char buf2[BUF_SZ];

    unsigned long host1 = 0x01020304;
    unsigned long host2 = 0xc0a80101;
    addr1.s_addr = htonl(host1);
    addr2.s_addr = htonl(host2);

    s = inet_ntoa(addr1);
    strncpy(buf1, s, BUF_SZ-1);
    buf1[BUF_SZ-1] = '\0';

    s = inet_ntoa(addr2);
    strncpy(buf2, s, BUF_SZ-1);
    buf2[BUF_SZ-1] = '\0';

    printf( "%#x -> %s.\n", addr1.s_addr, buf1 );
    printf( "%#x -> %s.\n", addr2.s_addr, buf2 );


    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值