For a homework question, i need to convert 64 bit int from host to network order in C. 64 bit int is stored in a union(as coded below) and is generated randomly by id_generator(see below). I'm trying to convert its order with the nw_order function and when i print it to control the order, they are just zeros. For example i get this output:
host order: 6D 5F E5 31
net order: 0 0 0 0
So, what i'm missing here?
union u
{
uint64_t u64;
uint32_t u32[2];
};
nw_order function takes two arguments and assign converted order of the first argument to the second:
void nw_order(const union u *host, union u *net)
{
net -> u32[0] = htonl(net->u32[1]);
net -> u32[1] = htonl(net->u32[0]);
}
i don't know if it causes problem but random generator function is:
uint64_t id_generator()
{
union u clientid;
if(sizeof(long) > 7)
clientid.u64 = (uint64_t)random();
else
{
clientid.u32[0] = (uint32_t)random();
clientid.u32[1] = (uint32_t)random();
}
return clientid.u64;
}
And the main function that prints before and after convertion:
int main()
{
union u client_id;
union u net;
unsigned char* p;
srandom(time(NULL));
client_id.u64 = (uint64_t) id_generator();
p = (unsigned char *) &client_id.u64;
printf("host order: %X %X %X %X\n",*p,*(p+1),*(p+2),*(p+3)); /* host ord*/
nw_order(&client_id, &net);
p = (unsigned char *) &net.u64;
printf("net order: %X %X %X %X\n",*p,*(p+1),*(p+2),*(p+3)); /* network ord*/
return 0;
}