Linux 服务器编程
  • Introduction
  • First Chapter
  • 文件I/O
    • 基于文件描述符的I/O操作
      • Linux 文件系统
      • 常用文件操作函数
    • 基于流的I/O操作
  • I/O模型
    • 概念理解
    • 对比五种I/O模型
    • select、poll、epoll简介
  • TCP / IP
    • OSI七层协议模型与TCP/IP四层模型
  • Socket
    • 基础
      • 什么是socket?
      • IPV4 套接口地址结构
      • 网络字节序
      • 字节序转换函数与地址转换函数
    • TCP客户端/服务器模型
    • Socket 相关函数
      • 使用socket()函数创建套接字
      • 使用bind()和connect()函数
      • 使用listen()和accept()函数
      • 使用read()和write()函数
    • 回射客户端/客户端的实现
    • 附录*资料
  • 附录*Linux常见信号
  • 多进程编程
    • 共享内存
    • fork函数
    • fork与vfork的区别
  • 附录*资料
  • 五种I/O模型
Powered by GitBook
On this page
  • 字节序转换函数
  • 示例
  • 地址转换函数
  • 为什么要有地址转换函数?

Was this helpful?

  1. Socket
  2. 基础

字节序转换函数与地址转换函数

字节序转换函数

常见的网络字节转换函数有:

  • unint16_t htons(uint16_t hostshort) => htons():host to network short,将short类型数据从主机字节序转换为网络字节序。

  • unint16_t ntohs(uint16_t netshort) => ntohs():network to host short,将short类型数据从网络字节序转换为主机字节序。

  • unint32_t htonl(uint32_t netlong) => htonl():host to network long,将long类型数据从主机字节序转换为网络字节序。

  • unint32_t ntohl(uint32_t hostlong) => ntohl():network to host long,将long类型数据从网络字节序转换为主机字节序。

通常,

以s为后缀的函数中,s代表2个字节short,因此用于端口号转换;

以l为后缀的函数中,l代表4个字节的long,因此用于IP地址转换。

例:htons() 用来将当前主机字节序转换为网络字节序,其中h代表主机(host)字节序,n代表网络(network)字节序,s代表short,htons 是 h、to、n、s 的组合,可以理解为”将short型数据从当前主机字节序转换为网络字节序“。

htonl ,htons 正好与 ntohl, ntohs 相反

可通过帮助命令 man htonl 查看帮助

示例

#include <stdio.h>

int main(void){
    unsigned int x = 0x12345678;
    unsigned char *p  = (unsigned char*)&x;
    printf("%0x_%0x_%0x_%0x\n", p[0], p[1], p[2], p[3]);

    unsigned int y = htonl(x);
    p  = (unsigned char*)&y;
    printf("%0x_%0x_%0x_%0x\n", p[0], p[1], p[2], p[3]);

    return 0;
}

我本机测试结果:

78_56_34_12
12_34_56_78

地址转换函数

为什么要有地址转换函数?

因为我们人为的能够认识的地址并不是32位的地址。给你一个32位的数值,我们并不知道 它的地址是什么样的. 我们习惯的地址是点分十进制的形式(192.168.0.100),而我们编程 的时候是指定的是32位的整数地址,所以就要引入地址转换函数。

头文件:

#include <netinet/in.h>
#include <arpa/inet.h>

函数说明:

in_addr_t inet_addr(const char *cp) => inet_addr():这表示将点分十进制的IP地址转换成32位的整数,通过返回值进行返回

char *inet_ntoa(struct in_addr in) => inet_ntoa: 这表示将一个地址结构转换成点分十进制的IP地址

int inet_aton(const char *cp,struct in_addr *inp) => inet_aton(): 这表示将点分十进制的IP地址转换成网络字节序的地址 ,只不过通过一个struct in_addr *inp地址结构输出(*inp输出参数)

注意:inet_addr() 除了将字符串转换为32位整数,同时还进行网络字节序转换。

Previous网络字节序NextTCP客户端/服务器模型

Last updated 5 years ago

Was this helpful?