字节序(网络/主机)转换
两种常用的相互转换:
主机字节序端口 <-----------> 网络字节序端口 (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;
}