C上的Memcpy和hostent结构

时间:2016-10-13 10:31:30

标签: c memcpy gethostbyname gethostbyaddr hostent

因此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_aliasesh_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_listdest struct的指针。

0 个答案:

没有答案