Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>an ip address is really just an array of <code>unsigned char</code>.</p> <pre><code>uchar ip[] = {127,0,0,1}; </code></pre> <p>Is a fine representation for a loopback address. But an array of four bytes, and a int really aren't that large; with one exception <strong>endiannes</strong>! So suppose I create the <code>int</code> which represents that ip. A naive approach might be:</p> <pre><code> int ip = (127&lt;&lt;24)|(0&lt;&lt;16)|(0&lt;&lt;8)|(1) </code></pre> <p>Of course, on <em>little endian</em> machines, like the x86 and arm it doing this:</p> <pre><code>char *char_ip = (void*)&amp;ip; </code></pre> <p>and iterating over that aray would yield:</p> <pre><code>1, 0, 0, 127 </code></pre> <p>But on a <em>big endian</em> machine, like a PowerPC, or a SPARC, we would have what we expect, </p> <pre><code>127, 0, 0, 1 </code></pre> <p>Big endian is also known as "network byte order" which is what the n in htonl stands for: "host to network long". These functions are frequently used when reading or writing integers over the network. Suppose a server wants to send a client some number:</p> <pre><code>uint32_t important = htonl(42); write(client, &amp;important, sizeof important); </code></pre> <p>Then, to read it, the client goes:</p> <pre><code>uint32_t important; read(server, &amp;important, sizeof important); important = ntohl(important); </code></pre> <p>The reason your ip address were flipped was because ip addresses are expected to be in network byte order, but yours were little endian instead. <code>htonl</code> on an <code>int</code>-type ip will flip it for you.</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