Comment définir SOCKADDR_IN6 :: SIN6_ADDR Ayte Commande à la commande d'octet de réseau?

StackOverflow https://stackoverflow.com/questions/6027989

Question

Je développe une application réseau et utiliser des API de socket.

Je veux définir l'ordre des octets SIN6_ADDR de Sockaddr_in6 Structure.

pour 16 bits ou 32 bits variables, c'est simple: en utilisant des jonces ou Htonl:

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

Mais pour 128 bits variables, je ne sais pas comment définir l'ordre d'octet à l'ordre d'octet de réseau:

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

Certaines réponses peuvent utiliser des joncages pour 8 fois (2 * 8= 16 octets) ou utiliser htonl pendant 4 fois (4 * 4= 16 octets), mais je ne sais pas de quelle manière est correcte.

merci.

Était-ce utile?

La solution

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

Autres conseils

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?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top