[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]
htons() and ntohs()
From: |
alaudo |
Subject: |
htons() and ntohs() |
Date: |
Wed, 5 Dec 2007 01:50:56 -0800 (PST) |
User-agent: |
G2/1.0 |
Hi,
I've got a strange problem with changing my unsigned short values from
host to the network byte order and vice versa.
I have a client and a server, which communicate via their own binary
protocol. I need to send some numerical values of unsigned short type,
so in the client I do the following:
typedef unsigned short order_id_t;
...
order_id_t orderNum; // variable declaration
...
/* I generate a binary message of MSG_LENGTH length and copy the id to
it */
void *msg; //binary message
msg = (void *) malloc(MSG_LENGTH);
orderNum = htons(orderNum);
memcpy(msg+OFFSET,&orderNum,sizeof(order_id_t));
/* Now I face a strange problem */
fprintf(stdout,"Your ID is:%d",ntohs(orderNum)); // here the correct
number is written to the stdout
fprintf(stdout,"Your ID is:%d",ntohs( (order_id_t) *(msg+OFFSET))); //
here t I get strange values, as if I had only the higher byte
// e.g., if orderNum is < 255, then I get 0, 256 gives me 256 correct,
257...260 all give 256 etc.
Any idea what could help here?
- htons() and ntohs(),
alaudo <=