title: Confused with network byte order and host byte order
body: <p>I'm getting terribly confused with <strong>host byte order</strong> and <strong>network byte order</strong>. I know network byte order is big endian. And I know host byte order in my case is little endian.</p>
  
  <p>So, if I'm printing data I would need to convert to host byte order in order to get the correct value right?</p>
  
  <p>My problem is I am trying to print the value of data returned by <code>htonl</code>. Here is my example:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;netinet/in.h&gt;
  
  int main(int argc, char *argv[])
  {   
      int bits = 12;
      char *ip = "132.89.39.0";
      struct in_addr addr;
      uint32_t network, netmask, last_addr;
      uint32_t total_hosts;
  
      inet_aton(ip, &amp;addr);
      printf("Starting IP:\t%s\n", inet_ntoa(addr.s_addr));
  
      netmask = (0xFFFFFFFFUL &lt;&lt; (32 - bits)) &amp; 0xFFFFFFFFUL;
      netmask = htonl(netmask);
      printf("Netmask:\t%s\n", inet_ntoa(netmask));
  
      network = addr.s_addr &amp; netmask;
      printf("Network:\t%s\n", inet_ntoa(network));
  
      printf("Total Hosts:\t%d\n", ntohl(netmask));
  
      return 0;
  </code></pre>
  
  <p>}                          </p>
  
  <p><code>printf("Total Hosts:\t%d\n", ntohl(netmask));</code> prints the correct value but it prints with a minus sign.If I use <code>%u</code>I get the wrong value.</p>
  
  <p>Where am I going wrong?</p>
  
  <p>With %d output is:</p>
  
  <pre><code>Starting IP:    132.89.39.0
  Netmask:        255.240.0.0
  Network:        132.80.0.0
  Total Hosts:    -1048576
  </code></pre>
  
  <p>With %u output is:</p>
  
  <pre><code>Starting IP:    132.89.39.0
  Netmask:        255.240.0.0
  Network:        132.80.0.0
  Total Hosts:    4293918720
  </code></pre>
  
  <p>I've been stuck on this for 2 days. Something seemingly so simple has threw me off completely. I don't want anyone to solve the problem, but a push in the right direction would be very helpful.</p>