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

## 字节序转换函数

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

* `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 查看帮助

### 示例

```c
#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位整数，同时还进行网络字节序转换。**


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://xiaoxiami.gitbook.io/linux-server/socket/ji-chu/zi-jie-xu-zhuan-huan-han-shu.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
