htons and ntohs


 
Thread Tools Search this Thread
Top Forums UNIX for Dummies Questions & Answers htons and ntohs
# 1  
Old 08-27-2008
htons and ntohs

Hi All,

I am running a short program on the effects of host-to-network and network-to-host functions. The following is part of my code:

int a = 384;
printf("Used htons with a, getting: %x Hex and %d Numeral\n", htons(a), htons(a));
printf("Used ntohs with a, getting: %x Hex and %d Numeral\n", ntohs(a), ntohs(a));
printf("Used htons(ntohs()) with a, getting: %x Hex and %d Numeral\n", htons(ntohs(a)), htons(ntohs(a)));
printf("Used ntohs(htons()) with a, getting: %x Hex and %d Numeral\n", ntohs(htons(a)), ntohs(htons(a)));

The following are the results:

Used htons with a, getting: 8001 Hex and 32769 Numeral
Used ntohs with a, getting: 8001 Hex and 32769 Numeral
Used htons(ntohs()) with a, getting: 180 Hex and 384 Numeral
Used ntohs(htons()) with a, getting: 180 Hex and 384 Numeral

I am using the program on a little-endian machine. I understand how 8001H and 32769 are derived but why are the first 2 results the same??
# 2  
Old 08-27-2008
Unless I missed something:
1.network default is big endian
2.those calls translate from the endianness of the box to network default

Assuming you used them correctly, they indicate your system is in network byte order.
It may be that in your unistd.h there is _SC_KERNEL_IS_BIGENDIAN defined. That will tell you what the C compiler thinks about system endianness, anyway.

What OS & platform?
 
Login or Register to Ask a Question

Previous Thread | Next Thread

2 More Discussions You Might Find Interesting

1. Programming

How to use htons() function?

Hi I am constructing an ICMP packet using C++ and want to convert sequence number into network byte order. I know we can use htons: here is my code: struct ICMPheader { unsigned int seqence_no; }; ICMPheader header; header.sequence_no = htons (sequence_no++); but it is giving... (3 Replies)
Discussion started by: manmeet
3 Replies

2. Programming

ntohs

" How do i write the function specifying the processor supports little-endian or big-endian"----May be similar to ntohs????? (1 Reply)
Discussion started by: chamarthi
1 Replies
Login or Register to Ask a Question