我是网络编程的新手。 以下结构定义对我来说非常混乱。 这里h_addr_list是一个定义为字符串数组,但是它用于存储in_addr结构数组。 为什么它没有定义为struct in_addr **h_addr_list而不是char **h_addr_list ?
struct hostent { char *h_name; /* Official domain name of host */ char **h_aliases; /* Null-terminated array of domain names */ int h_addrtype; /* Host address type (AF_INET) */ int h_length; /* Length of an address, in bytes */ char **h_addr_list; /* Null-terminated array of in_addr structs */ }; struct in_addr { unsigned int s_addr; /* Network byte order (big-endian) */ };I am new to network programming. The following structure definitions are quite confusing to me. Here h_addr_list is a defined as string array, but it is used to store array of in_addr structures. Why didn't it define as struct in_addr **h_addr_list rather than char **h_addr_list?
struct hostent { char *h_name; /* Official domain name of host */ char **h_aliases; /* Null-terminated array of domain names */ int h_addrtype; /* Host address type (AF_INET) */ int h_length; /* Length of an address, in bytes */ char **h_addr_list; /* Null-terminated array of in_addr structs */ }; struct in_addr { unsigned int s_addr; /* Network byte order (big-endian) */ };最满意答案
结构定义可以追溯到C之前支持void * (或者void或者prototype)的时代。 在那些日子里, char *是'通用指针'。 这解释了网络功能接口的一些奇怪之处。
它也可以追溯到有许多不同网络系统(IPX / SPX,SNA,TCP / IP等)的时代。 现在,TCP / IP是占主导地位的,但即使是现在,您也可能会返回一组IPv4地址或一组IPv6地址,因此指定struct in_addr或struct in6_addr会导致问题。
目的是你有一个指向适当结构类型的指针数组。 现在,它将被写入void **h_addr_list - 一个void *数组。 但是当这个结构第一次被定义时,这个选项是不可用的,剩下的就是历史了(如果你可以避免它的话,你不需要在接口被标准化后改变接口)。
The structure definition dates back to the era before C supported void * (or void at all, or prototypes). In those days, char * was the 'universal pointer'. This accounts for some of the weirdnesses of the networking function interfaces.
It also dates back to the era when there were many different networking systems (IPX/SPX, SNA, TCP/IP, …). These days, TCP/IP is dominant, but even now, you could have an array of IPv4 or an array of IPv6 addresses being returned, so specifying either struct in_addr or struct in6_addr would cause problems.
The intention was that you'd have an array of pointers to appropriate structure types. Nowadays, it would be written void **h_addr_list — an array of void *. But this option was not available when the structures were first defined, and the rest is history (you don't change an interface after it is standardized if you can avoid it).
更多推荐
发布评论