一、字节序转换函数
转换端口
uint16_t htons(uint16_t hostshort); //主机字节序->网络字节序
uint16_t ntohs(uint16_t netshort); //网络字节序->主机字节序
转IP
uint32_t htons(uint32_t hostlong);//主机字节序->网络字节序
uint32_t ntohs(uint32_t netlong);//网络字节序->主机字节序
二、使用步骤
#include<stdio.h>
#include<arpa/inet.h>
int main()
{
//htons 转换端口
unsigned short a=0x0102;
printf("%x\n",a);
unsigned short b=htons(a);
printf("%x\n",b);
printf("--------------------------------\n");
//htonl 转换IP
char buf[4]={192,168,1,100};
int num=*(int *)buf;
int res=htonl(num);
unsigned char* p=(char*)&res;
printf("%d %d %d %d\n",*p,*(p+1),*(p+2),*(p+3));
printf("--------------------------------\n");
//ntohs
unsigned char buf1[4]={1,1,168,192};
int num1=*(int*)buf1;
int res1=ntohl(num1);
unsigned char* p1=(unsigned char*)&res1;
printf("%d %d %d %d\n",*p1,*(p1+1),*(p1+2),*(p1+3));
printf("--------------------------------\n");
//ntohl
unsigned int c=0x12345678;
printf("%x\n",c);
unsigned int d=htonl(c);
printf("%x\n",d);
return 0;
}
总结
本节主要介绍了字节序转换函数,以便在实际开发中使用。