当前位置:网站首页>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;
}
边栏推荐
- AcWing 1986. 镜子(模拟,环图)
- Les humains veulent de l'argent, du pouvoir, de la beauté, de l'immortalité, du bonheur... Mais les tortues ne veulent être qu'une tortue.
- Socket programming UDP
- Zabbix 监控之LLD
- 你需要社交媒体二维码的21个理由
- Get all listening events in the element
- 字节序 - 如何判断大端小端
- M-Arch(番外12)GD32L233评测-CAU加解密(捉弄下小编)
- C# 36. DataGridView行号
- DrQueueOnRails 集成 LDAP 验证
猜你喜欢

人類想要擁有金錢、權力、美麗、永生、幸福……但海龜只想做一只海龜

【clickhouse专栏】基础数据类型说明

字节序 - 如何判断大端小端

scanf返回值被忽略的原因及其解决方法

Les humains veulent de l'argent, du pouvoir, de la beauté, de l'immortalité, du bonheur... Mais les tortues ne veulent être qu'une tortue.

Redis summary

AcWing 128. Editor (to effectively modify the specified position in the top stack)

Unity connect to Microsoft SQLSERVER database

Clickhouse column basic data type description

Windows10 install mysql-8.0.28-winx64
随机推荐
C# 35. Select default network card
M-Arch(番外10)GD32L233评测-SPI驱动DS1302
postman传入list
AcWing 1921. Rearranging cows (ring diagram)
35. 搜索插入位置
The difference between meta universe chain games and traditional games
MySQL45讲 01 | 基础架构:一条SQL查询语句是如何执行的?
套接字实现 TCP 通信流程
^34作用域面试题
A simple understanding of b+ tree
Simple solution of regular expression
Construction and construction of meta Universe System
Epidemic home office experience | community essay solicitation
AcWing 1912. Odometer (enumeration)
^34 scope interview questions
Distributed storage exploration
Socket Programming TCP
多普勒效应的基本原理
字节序(网络/主机)转换
元宇宙系统搭建与构造