title: htons() function in socket programing
body: <p>I am new to socket programming and I am  trying to understand the operation of <code>htons()</code>. I've read a few tutorials on the Internet like <a href="http://www.beej.us/guide/bgnet/output/html/multipage/htonsman.html">this</a> and <a href="http://www.tutorialspoint.com/unix_sockets/network_byte_orders.htm">this</a> one for instance. But I couldn't understand what <code>htons()</code> does exactly. I tried the following code:</p>
  
  <pre><code>#include &lt;stdio.h&gt;
  #include &lt;sys/types.h&gt; 
  #include &lt;sys/socket.h&gt;
  #include &lt;netinet/in.h&gt;
  
  int main( int argc, char *argv[] )
  {
      int sockfd, newsockfd, portno, clilen;
      char buffer[256];
      struct sockaddr_in serv_addr, cli_addr;
      int  n;
  
      /* First call to socket() function */
      sockfd = socket(AF_INET, SOCK_STREAM, 0);
      if (sockfd &lt; 0) 
      {
          perror("ERROR opening socket");
          exit(1);
      }
      /* Initialize socket structure */
      bzero((char *) &amp;serv_addr, sizeof(serv_addr));
      portno = 5001;
      serv_addr.sin_family = AF_INET;
      serv_addr.sin_addr.s_addr = INADDR_ANY;
      serv_addr.sin_port = htons(portno);
  
      /* Now bind the host address using bind() call.*/
      if (bind(sockfd, (struct sockaddr *) &amp;serv_addr,
                            sizeof(serv_addr)) &lt; 0)
      {
           perror("ERROR on binding");
           exit(1);
      }
  
      /* Now start listening for the clients, here process will
      * go in sleep mode and will wait for the incoming connection
      */
      listen(sockfd,5);
      clilen = sizeof(cli_addr);
  
      /* Accept actual connection from the client */
      newsockfd = accept(sockfd, (struct sockaddr *)&amp;cli_addr, 
                                  &amp;clilen);
      if (newsockfd &lt; 0) 
      {
          perror("ERROR on accept");
          exit(1);
      }
      /* If connection is established then start communicating */
      bzero(buffer,256);
      n = read( newsockfd,buffer,255 );
      if (n &lt; 0)
      {
          perror("ERROR reading from socket");
          exit(1);
      }
      printf("Here is the message: %s\n",buffer);
  
      /* Write a response to the client */
      n = write(newsockfd,"I got your message",18);
      if (n &lt; 0)
      {
          perror("ERROR writing to socket");
          exit(1);
      }
      return 0; 
  }
  </code></pre>
  
  <p>The value of <code>sin_port</code> was shown as <code>35091</code> while debugging and I don't understand how <code>portno</code> changed from <code>5001</code> to <code>35091</code>. Could someone explain the reason for that change in value please?</p>