How to set sockaddr_in6::sin6_addr byte order to network byte order?
Asked Answered
P

2

10

I developing a network application and using socket APIs.

I want to set sin6_addr byte order of sockaddr_in6 structure.

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);

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?

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.

Thanks.

Punk answered 17/5, 2011 at 8:8 Comment(0)
L
16

The s6_addr member of struct in6_addr is defined as:

uint8_t s6_addr[16];

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);
Loya answered 18/5, 2011 at 5:34 Comment(1)
Basically you are imposing network order (big endian) using this methodKiddy
L
0

The usual thing would be to use one of the hostname lookup routines and use the result of that, which is already in network byte order. How come you're dealing with hardcoded numeric IP addresses at all?

Lucubration answered 17/5, 2011 at 9:53 Comment(2)
honestly, I develope a library. There are some limitations for accessing hostname.Punk
@Amir Saniyan What limitations? The entire Internet uses hostnames rather than IP addresses, and delegates the latter to a database called DNS. What's different about your situation? In any case all you have to do is store the IP address in octets, i.e. bytes, same order as you would write them, and job done.Lucubration

© 2022 - 2024 — McMap. All rights reserved.