当前位置:网站首页>Byte order (network / host) conversion
Byte order (network / host) conversion
2022-06-12 11:29:00 【Investment paranoia】
Byte order ( The Internet / host ) transformation
Two common conversions :
Host byte order port <-----------> Network byte order port (uint16_t <----------------> uint16_t)
IPv4 character string <----------------> Network byte order 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;
}
边栏推荐
猜你喜欢

模块8作业

Distributed storage exploration

程序分析与优化 - 6 循环优化

M-arch (fanwai 11) gd32l233 evaluation PWM driven active buzzer

logrotate日志轮转方式create和copytruncate原理

M-Arch(番外13)GD32L233评测-来点音乐

Unity connect to Microsoft SQLSERVER database

VirtualBox 虚拟机因系统异常关机虚拟机启动项不见了

Socket programming UDP

InfoQ geek media's 15th anniversary solicitation |position:fixed virtual button cannot take effect after being triggered. Problem analysis and Solution Exploration
随机推荐
LVS health state detection based on application layer
C# 36. DataGridView line number
Selenium uses proxy IP
Redis summary
systemctl里万恶的203
k52.第一章 基于kubeadm安装kubernetes v1.22 -- 集群部署
Arm cross compilation chain download address
M-Arch(番外12)GD32L233评测-CAU加解密(捉弄下小编)
go基于阿里云实现发送短信
Pessimistic lock and optimistic lock of MySQL
FormatConversionTool.exe
MCUXpresso开发NXP RT1060(3)——移植LVGL到NXP RT1060
【蓝桥杯单片机 国赛 第十一届】
AcWing 132. Group queue (queue simulation question)
B+ 树的简单认识
Grid layout
Leetcode 162 Looking for peak value (June 11, 2022)
UI自动化测试中比较少见的异常记录
35. search insertion position
人類想要擁有金錢、權力、美麗、永生、幸福……但海龜只想做一只海龜