字节序
小端字节序:数据低位存于内存低地址;
大端字节序:数据低位存于内存高地址;也叫 “网络字节序” 。
数据要先转为网络字节序才能在网络上传输。
(1)字节序转换函数
#include<arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
/*
IPV4地址 转为 网络字节序
*/
uint16_t htons(uint16_t hostshort);
/*
port 转为 网络字节序
*/
uint32_t ntohl(uint32_t netlong);
/*
IPV4地址 转为 主机字节序
*/
uint16_t ntohs(uint16_t netshort);
/*
port 转为 主机字节序
*/
使用示例
#include<arpa/inet.h>
#include<stdio.h>
int main(int argc, const char* argv[]) {
/*主机字节序转为网络字节序*/
unsigned char buf[4] = { 192, 168, 1, 2 };
unsigned int oriGnum = *(int*)buf; // 将buf转为int型地址可得到连续4个字节的数据
unsigned int transNum = htonl(oriGnum);
unsigned char* p = (unsigned char*)&transNum;
printf("%u, %u, %u, %u\n", *p, *(p + 1), *(p + 2), *(p + 3));
unsigned short a = 0x0102;
unsigned short b = htons(a);
printf("%x\n", b);
return 0;
}
运行结果:
(2)IP地址转换函数
#include<arpa/inet.h>
int inet_pton(int af, const char* src, void* dst);
/*
功能:
点分十进制IPV4或IPV6地址字符串src 转为 网络字节序,存入dst指向的空间
参数:
af:
AF_INET:IPV4
AF_INET6:IPV6
src:点分十进制IP地址字符串的地址
dst:存储转换后网络字节序的地址
返回值:
成功:1
失败:0 或 -1
*/
const char* inet_ntop(int af, const void* src, char* dst, socklen_t size);
/*
功能:
IPV4或IPV6地址网络字节序src 转为 点分十进制字符串,存入dst指向的空间
参数:
af:
AF_INET:IPV4
AF_INET6:IPV6
src:点分十进制IP地址字符串的地址
dst:存储转换后点分十进制字符串的地址
size:dst指向空间的大小,通常为16字节
返回值:
成功:存储点分十进制字符串的地址
失败:NULL
*/
使用示例
#include<arpa/inet.h>
#include<stdio.h>
#include<string.h>
int main(int argc, const char* argv[]) {
/*inet_pton*/
unsigned char buf[] = "192.168.1.4";
unsigned int num = 0;
inet_pton(AF_INET, buf, &num);
unsigned char* p = (unsigned char*)#
printf("inet_pton: %d %d %d %d\n", *p, *(p + 1), *(p + 2), *(p + 3));
/*inet_ntop*/
char buf1[16];
memset(buf1, 0, 16);
inet_ntop(AF_INET, &num, buf1, 16);
printf("inet_ntop: %s\n", buf1);
return 0;
}
运行结果: