Pregunta

Desarrollé una aplicación de red y uso de API de socket.

Quiero configurar SIN6_ADDR BYTE ORDEN DE ESTRUCTURA SOCKADDR_IN6.

Para 16 bits o 32 bits variables, es simple: usando hons o htonl:

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

Pero para las variables de 128 bits, no sé cómo establecer el registro de bytes a la orden de byte de la red:

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

Algunas respuestas pueden estar usando hons para 8 veces (2 * 8= 16 bytes), o usando HTONL durante 4 veces (4 * 4= 16 bytes), pero no sé de qué manera es correcta.

gracias.

¿Fue útil?

Solución

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

Otros consejos

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?

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top