简体   繁体   中英

Why are linux's IPv4 address taking 16 bytes instead of 4

I'm trying to resolve a domain name to an ipv4 address.

Here's a minimal code of what I'm doing

addrinfo hints, *results;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET;
int error = getaddrinfo("google.com", 0, &hints, &results);
for(addrinfo* info = results; info; info = info->ai_next)
{
    std::cout << (info->ai_family == AF_INET6 ? "ip6" : "ip4")
              << '[' << info->ai_addrlen << "]: ";
    for(uint i = 0; i < info->ai_addrlen; ++i)
        std::cout << int(((uint8_t*)info->ai_addr)[i]) << ' ';
    std::cout << std::endl;
}
freeaddrinfo(results);

When I run this, it prints:

ip4[16]: 2 0 0 0 216 58 208 238 0 0 0 0 0 0 0 0 
ip4[16]: 2 0 0 0 216 58 208 238 0 0 0 0 0 0 0 0 
ip4[16]: 2 0 0 0 216 58 208 238 0 0 0 0 0 0 0 0

The actual ip of google.com is 216.58.208.238 . So for some reason, for ip v4, ai_addr contains 16 bytes and actually stores the address at bytes 4 to 8.

My question is: what are the 12 other bytes for ?

I read the docs , and googled a bit but found nothing on addr_len . Also note that I didn't set the AI_V4MAPPED flag.

I'm not sure whether this is actually required by some standard, but struct sockaddr is defined to contain a short for the address family and then 14 bytes of address-family-specific data.

Every type used as an address must be compatible with that, thus, be at least the same length.

For struct sockaddr_in (the one for IPv4), it looks like this:

struct sockaddr_in {
    short            sin_family;
    unsigned short   sin_port;
    struct in_addr   sin_addr;
    char             sin_zero[8];
};

2 bytes for the address family, 2 bytes for the port, 4 bytes for the IPv4 address and 8 bytes of padding to reach the length of struct sockaddr .

That said: Your question is slightly wrong, this is not an IPv4 address (that would be just struct in_addr which is indeed just 4 bytes) but a socket address for IPv4. Still, 8 bytes are "wasted" here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM