Pregunta

I am writing a wrapper for gethostbyname() function, which, before returning a pointer to the hostent structure, should allow for executing getaddrinfo() and eventually mapping the returned IPv6 structures to the IPv4 ones. However, I am having a problem with casting the returned in_addr structures properly in order to populate the h_addr_list of hostent addresses - in case the family identified equals AF_INET, of course.

I am basically doing the following:

strcpy(&s[0],name);
hp->h_name = strdup(s);
hp->h_addrtype = AF_INET;
hp->h_length = sizeof(struct in_addr);
struct sockaddr *sa= res->ai_addr;

// Segmentation fault:
memcpy(hp->h_addr_list[0], &(((struct sockaddr_in *)sa)->sin_addr.s_addr), hp->h_length);

Any hints? I haven't written any C code in a long time, so sorry if I am asking a stupid question. Thanks.

¿Fue útil?

Solución 2

Ok, allocating blocks for the hostent and h_addr_list worked for me, some more context:

hp=(struct hostent *)calloc(1,sizeof(struct hostent));

hp->h_name = strdup(s);
hp->h_aliases = NULL;
hp->h_addrtype = AF_INET;
hp->h_length = sizeof(struct in_addr);
hp->h_addr_list = (char **)calloc(2,sizeof(char *));
hp->h_addr_list[0] = calloc(1,4);
struct sockaddr *sa = res->ai_addr;

memcpy(hp->h_addr_list[0], (char *)&(((struct sockaddr_in *)sa)->sin_addr.s_addr), hp->h_length);

Otros consejos

The s_addr member (in e.g. saddr->sin_addr.s_addr) is not a pointer. You have to use the address-of operator to make it a pointer.

And hp->h_addr_list[0] is a pointer, so when you use the address-of operator here, you get the address of that pointer, and will copy to the completely wrong address.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top