当前位置:网站首页>字节序(网络/主机)转换
字节序(网络/主机)转换
2022-06-12 11:23:00 【爱投资的偏执狂】
字节序(网络/主机)转换
两种常用的相互转换:
主机字节序端口 <-----------> 网络字节序端口 (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;
}
边栏推荐
猜你喜欢
随机推荐
FormatConversionTool.exe
对网络库协程的思考——读brpc有感
AcWing 132. Group queue (queue simulation question)
Leetcode 162 Looking for peak value (June 11, 2022)
Clickhouse column basic data type description
重量级代理缓存服务器Squid
Pytorch笔记
K59. Chapter 2 installing kubernetes V1.23 based on binary packages -- cluster deployment
力扣(LeetCode)162. 寻找峰值(2022.06.11)
AcWing 128. Editor (to effectively modify the specified position in the top stack)
DS18B20 digital thermometer (I) electrical characteristics, power supply and wiring mode
Clickhouse column basic data type description
深度学习与CV教程(14) | 图像分割 (FCN,SegNet,U-Net,PSPNet,DeepLab,RefineNet)
卡鱼刺别再喝醋吞米饭了!教你2招,让鱼刺安全“跑出来”
M-arch (fanwai 11) gd32l233 evaluation PWM driven active buzzer
ReentrantLock源码分析
MYSQL——内置函数
M-Arch(番外12)GD32L233评测-CAU加解密(捉弄下小编)
Differences among various cross compiling tools of arm
【CF1392D】D. Omkar and Bed Wars(环形与后效性dp)









