简体   繁体   中英

C - Casting “h_addr_list” array to type “struct in_addr **”

I'm reading this tutorial: here But I can't understand how this part works. Casting from char** to a struct in_addr ** that contains an unsigned long seems weird.

// Cast the h_addr_list to in_addr 
// since h_addr_list also has the ip address in long format only
addr_list = (struct in_addr **) he->h_addr_list;

I wish someone could explain what's happening and how the code works.

EDIT: To be more specific: I want to know how can the compiler understand what we are trying to do here ? why should this code be correct ?

When you call gethostbyname , it returns a pointer to a struct hostent . One of the fields in this struct, h_addr_list , is an array of pointers to network addresses.

Since a network address can be either a struct in_addr for an IPv4 address or a struct in6_addr for an IPv6 address, h_addr_list is defined as a char ** as a generic type that can point to either one. The h_addrtype field tells you which one of these is valid.

Once you know that, you cast h_addr_list to either struct in_addr ** or struct in6_addr ** as appropriate, then access each element in the array.

EDIT:

Pointers between either void or char types and any other non-function type can freely be casted to or from each other.

In this particular case, it's likely that gethostbyname has a static char buffer that it casts to a struct in_addr ** or a struct in6_addr ** as appropriate in order to create the array. Then the calling function performs the same cast in order to get the values out.

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