Passing structures using UDP
I have been trying to send and receive structures on the same machine using UDP and the server and client in this case run on the same machine and share common structure definitions (using a header file).
Hostent structure defn(UNIX built-in type) :
struct hostent{
char *h_name;
char **h_aliases;
int h_addrtype;
int h_length;
char **h_addr_list;
}
Server Code snippet follows :
struct hostent* resolved_host = DNS_translate(DNSname);
if((numbytes = sendto(sockfd, (void*)&resolved_host, sizeof(struct hostent), 0, (struct sockaddr *)&client_addr, sizeof(struct sockaddr))) == -1)
{
perror("sendto failed");
exit(EXIT_FAILURE);
}
Client Code snippet follows:
struct hostent resolved_host;
int addr_len = sizeof(struct sockaddr);
if((numbytes = recvfrom(sockfd, (void*)&resolved_host, sizeof(struct hostent), 0, (struct sockaddr *)&server_addr, &addr_len)) == -1)
{
perror("recvfrom failed");
exit(EXIT_FAILURE);
}
The server sends and the client receives as normal (no error raised). The *resolved_host* structure 开发者_如何学Gois filled in the server and all its data can be accessed with no problem. However, if I now try to use the *resolved_host* structure in the client, I get a seg fault. For example:
printf("Name : %s\n", resolved_host.h_name);
raises a seg fault. (but works in the server)
Your struct is full of pointers. When you send it over the network, you send the actual addresses, not the data pointed to by those pointers.
Those addresses are invalid in the target process.
You will need to serialize the data yourself. See for examples:
Serialization/Deserialization of a struct to a char* in C
Serialization techniques
The structure contains pointers - so when you copy the structure over UDP you're only copying the values of those pointers (i.e. the addresses of some other pieces of data) and not the actual data itself.
When you receive those pointers in the server they no longer mean anything - those pointer addresses are meaningless to the other program.
You are sending pointers. Even on the same machine these are not valid in different address spaces.
精彩评论