Socket中字节序转换常用函数

注:仅用作个人学习自用!

参考博客:

Socket编程:必须要了解的网络字节序和转换函数_socket 字节序-CSDN博客

1.大端小端介绍

大端字节序:高位字节存储在内存的低地址处,低位字节存储在内存的高地址处

小端字节序:高位字节存储在内存的高地址处,而低位字节存储在内存的低地址处

2.主机序和网络序转换API

函数说明:从主机字节序转换到网络字节序(大端 32位)

/* 方便记忆
* h:host 
* n:net
* l:long
* s:short
*/
unsigned long int htonl ( unsigned long int hostlong)

unsigned short int htons ( unsigned short int hostlong )

 函数说明:从网络字节序转换到主机字节序

unsigned long int ntohl ( unsigned long int netlong )

unsigned short int ntohs ( unsigned short int netshort )

 测试结果:

unsigned long a = 0x01020304;
printf("init %#x after htonl %#x\r\n",a,htonl(a));

unsigned short b = 0x1234;
printf("init %#x after htons %#x\r\n",b, htons(b));

Output:
init 0x1020304 after htonl 0x4030201
init 0x1234 after htons 0x3412

 补充:长整型函数通常用来 IP 地址的转换,短整型函数用于端口号的转换

3.IP地址转换

函数说明:将用点分十进制表示的IPv4地址转换为网络字节序的32位二进制数  

//返回值:in_addr类型(uint32_t)
in_addr_t inet_addr( const char *strptr )

函数说明:将用网络字节序整数表示的 IPv4 地址转化为用点分十进制字符串表示的 IPv4 地址

//返回值:字符串
char * inet_ntoa( struct in_addr in )

测试结果

void testinet(void)
{
    const char *str = "127.0.0.1";
    uint32_t a = 0x100007f;
    struct in_addr in;
    memcpy(&in,&a,sizeof(uint32_t));
    printf("%#x\r\n",inet_addr(str));
    printf("%s\r\n", inet_ntoa(in));
}


Output:
0x100007f
127.0.0.1

  • 7
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值