概念
网络字节序:高位字节低位地址存储,低位字节高位地址存储
主机字节序:高位字节高位地址存储,低位字节低位地址存储
define实现
#include "stdio.h"
#include <arpa/inet.h>
#define BigLittleSwap(A) ((((int)(A) & 0xff000000) >> 24) | (((int)(A) & 0x00ff0000) >> 8) | (((int)(A) & 0x0000ff00) << 8) | (((int)(A) & 0x000000ff) << 24))
int main(int argc, char **argv)
{
uint32_t src_ip, dst_ip;
src_ip = inet_addr("192.168.2.201");
unsigned char dst_ip1[32] = "192.168.2.200";
dst_ip = inet_addr(dst_ip1);
BigLittleSwap(src_ip);
BigLittleSwap(dst_ip);
printf("[src_ip]:%p\t[dst_ip]:%p\n", src_ip, dst_ip);
printf("[src_ip]:%p\t[dst_ip]:%p\n", htonl(src_ip), ntohl(dst_ip));
return 0;
}
C语言库函数
#include <arpa/inet.h>
uint32_t htonl(uint32_t hostlong);
//hostlong:主机字节顺序表达的32位数。
htonl:将主机数转换成无符号长整型的网络字节顺序。
htons:将主机的无符号短整形数转换成网络字节顺序。
ntohl:是将一个无符号长整形数从网络字节顺序转换为主机字节顺序。
ntohs:作用是将一个16位数由网络字节顺序转换为主机字节顺序。