I send a struct with one field (unsigned int) to a network emulator and it outputs the unsigned int but it is incorrect.
If I do NOT re-run the network emulator, if I resend the struct with the same number, it will be the same random integer. If I send that number +1, I get the random integer -1.
If i do re-run the network emulator and resend the struct with the same number, it shows a different random integer.
This is the stuct:
struct pkt_INIT {
unsigned int router_id;
};
This is the code to send that struct:
int sock;
struct sockaddr_in server_addr;
struct hostent *host;
char send_data[1024];
host= (struct hostent *) gethostbyname(emulator_host);
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
perror("socket");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(emulator_port);
server_addr.sin_addr = *((struct in_addr *)host->h_addr);
bzero(&(server_addr.sin_zero),8);
struct pkt_INIT init;
init.router_id = router_id;
strcpy(send_data,(char *)&init);
sendto(sock, send_data, strlen(send_data), 0,
(struct sockaddr *)&server_addr, sizeof(struct sockaddr));
I don’t have any of the code for the network emulator.
Don’t use
strcpy()to put a binary struct into a binary array. Likewise, do not usestrlen()to get the length of a struct. Both functions are designed for strings, and will copy/read bytes until they encounter a null byte. Usememcpy()andsizeof()instead:In which case, just get rid of the array and pass the struct directly to
sendto()instead:Now, with that said, there is an issue with the router_id. Most network protocols require network byte ordering, so you may or may not need to use
htonl(), depending on what the emulator is actually expecting: