字节序(网络/主机)转换

字节序(网络/主机)转换

两种常用的相互转换:

主机字节序端口 <-----------> 网络字节序端口 (uint16_t <----------------> uint16_t)

IPv4字符串 <----------------> 网络字节序IPv4 (const char * <----------> unsigned int)

/*********************************************************
Copyright © 2022 Shengkai Liu. All rights reserved.
FileName:   byte_conversion.c
Author:     Shengkai Liu
Date:       2022-05-30
***********************************************************/

#include <stdio.h>          // printf
#include <arpa/inet.h>      // htons, ntohs, inet_pton, inet_ntop
#include <assert.h>         // assert
#include <string.h>         // strcmp

#define HOST_PORT 12345
#define IP  "127.0.0.1"

int main()
{
    
    printf("port before conversion: 0x%x \n", HOST_PORT);

    // 1. host to network (unsigned short int)
    uint16_t network_port = htons(HOST_PORT);

    printf("port after conversion: 0x%x\n", network_port);

    // 2. network to host (unsigned short int)
    uint16_t host_port = ntohs(network_port);
    assert(host_port == HOST_PORT);

    
    printf("IPv4 before conversion: %s\n", IP);

    // 3. string of IPv4 to network (unsigned int)
    unsigned int ip_num = 0;
    inet_pton(AF_INET, IP, &ip_num);

    printf("IPv4 after conversion: %d\n", ip_num);

    // 4. network to string of IPv4 (char *)
    char ip_addr[16];
    inet_ntop(AF_INET, &ip_num, ip_addr, sizeof(ip_addr));
    assert(strcmp(IP, ip_addr) == 0);

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值