所以gethostbyaddr()
返回一个hostent
.
struct hostent {
char *h_name; /* official name of host */
char **h_aliases; /* alias list */
int h_addrtype; /* host address type */
int h_length; /* length of address */
char **h_addr_list; /* list of addresses */
理论上,memcpy
我们不能将这个结构复制到另一个hostent
,因为h_aliases
and h_addr_list
。
所以我测试了在 C 上做一段代码。
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
int main() {
int i;
unsigned char ip[] = {130, 206, 192, 10};
char name[14]="www.apple.com";
struct hostent *initial, *final;
struct in_addr IP;
if ((initial = gethostbyaddr(ip, sizeof (ip), AF_INET)) == NULL)
exit(EXIT_FAILURE);
memcpy(&final, &initial, sizeof(initial)); //memcpy(*dest, *initial, size)
printf("HOST: %s\n", final -> h_name);
for (i = 0; final->h_aliases[i] != NULL; i++)
printf("ALIASES[%d]: %s\n", i, final -> h_aliases[i]);
for (i = 0; final->h_addr_list[i] != NULL; i++) {
IP.s_addr = *((uint32_t*) final->h_addr_list[i]);
printf("IP[%d]: %s\n\n", i, inet_ntoa(IP));
}
if ((initial = gethostbyname(name)) == NULL)
exit(EXIT_FAILURE);
printf("HOST: %s\n", final -> h_name);
for (i = 0; final->h_aliases[i] != NULL; i++)
printf("ALIASES[%d]: %s\n", i, final -> h_aliases[i]);
for (i = 0; final->h_addr_list[i] != NULL; i++) {
IP.s_addr = *((uint32_t*) final->h_addr_list[i]);
printf("IP[%d]: %s\n\n", i, inet_ntoa(IP));
}
}
代码的输出是:
HOST: a130-206-192-10.deploy.akamaitechnologies.com
IP[0]: 130.206.192.10
HOST: a130-206-192-10.deploy.akamaitechnologies.com
IP[0]: 130.206.192.10
正如你所看到的,同样的东西被打印了两次。它不应该第二次打印与Apple相关的东西吗?因为当我这样做时,memcpy
我复制了h_aliases
和h_addr_list
的指针dest struct
。