Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's a portable way of converting Byte-Order of strings in C
    text
    copied!<p>I am trying to write server that will communicate with any standard client that can make socket connections (e.g. telnet client)</p> <p>It started out as an echo server, which of course did not need to worry about network byte ordering.</p> <p>I am familiar with ntohs, ntohl, htons, htonl functions. These would be great by themselves if I were transfering either 16 or 32-bit ints, or if the characters in the string being sent were multiples of 2 or 4 bytes.</p> <p>I'd like create a function that operates on strings such as:</p> <pre><code>str_ntoh(char* net_str, char* host_str, int len) { uint32_t* netp, hostp; netp = (uint32_t*)&amp;net_str; for(i=0; i &lt; len/4; i++){ hostp[i] = ntoh(netp[i]); } } </code></pre> <p>Or something similar. The above thing assumes that the wordsize is 32-bits. We can't be sure that the wordsize on the sending machine is not 16-bits, or 64-bits right?</p> <p>For client programs, such as telnet, they must be using hton* before they send and ntoh* after they receive data, correct?</p> <p>EDIT: For the people that thing because 1-char is a byte that endian-ness doesn't matter:</p> <pre><code>int main(void) { uint32_t a = 0x01020304; char* c = (char*)&amp;a; printf("%x %x %x %x\n", c[0], c[1], c[2], c[3]); } </code></pre> <p>Run this snippet of code. The output for me is as follows:</p> <pre><code>$ ./a.out 4 3 2 1 </code></pre> <p>Those on powerPC chipsets should get '1 2 3 4' but those of us on intel chipset should see what I got above for the most part.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload