如何将sockaddr_in6 :: sin6_addr字节顺序设置为网络字节顺序? [英] How to set sockaddr_in6::sin6_addr byte order to network byte order?

查看:501
本文介绍了如何将sockaddr_in6 :: sin6_addr字节顺序设置为网络字节顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发网络应用程序并使用套接字API。

I developing a network application and using socket APIs.

我想设置sockaddr_in6结构的sin6_addr字节顺序。

I want to set sin6_addr byte order of sockaddr_in6 structure.

对于16位或32位变量,很简单:使用htons或htonl:

For 16 bits or 32 bits variables, it is simple: Using htons or htonl:

// IPv4
sockaddr_in addr;
addr.sin_port = htons(123);
addr.sin_addr.s_addr = htonl(123456);

但是对于128位变量,我不知道如何将字节顺序设置为网络字节顺序:

But for 128 bits variables, I dont know how to set byte order to network byte order:

// IPv6
sockaddr_in6 addr;
addr.sin6_port = htons(123);
addr.sin6_addr.s6_addr = ??? // 16 bytes with network byte order but how to set?

某些答案可能是使用htons进行了8次(2 * 8 = 16字节),或者使用了htonl 4次(4 * 4 = 16字节),但我不知道哪种方法是正确的。

Some answers may be using htons for 8 times (2 * 8 = 16 bytes), or using htonl for 4 times (4 * 4 = 16 bytes), but I don't know which way is correct.

谢谢。

推荐答案

struct in6_addr s6_addr 成员定义为:

uint8_t s6_addr[16];

由于它是 uint8_t 的数组,而不是单个128位整数类型,不会出现字节顺序问题:您只需从源 uint8_t [16] 数组复制到目标即可。例如,要复制地址 2001:888:0:2:0:0:0:2 ,您可以使用:

Since it is an array of uint8_t, rather than being a single 128-bit integer type, the issue of endianness does not arise: you simply copy from your source uint8_t [16] array to the destination. For example, to copy in the address 2001:888:0:2:0:0:0:2 you would use:

static const uint8_t myaddr[16] = { 0x20, 0x01, 0x08, 0x88, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 };

memcpy(addr.sin6_addr.s6_addr, myaddr, sizeof myaddr);

这篇关于如何将sockaddr_in6 :: sin6_addr字节顺序设置为网络字节顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆