title: Sending 'signed long int' via sockets
body: <p>I am trying to send a long int number using sockets (from client to server).
  Both the client and the server are x86 (and identical machines). The client writes 21 long int's to the socket and the server reads it out.</p>
  
  <p>Here is a part of the code.</p>
  
  <p>Server:</p>
  
  <pre><code>long int num = 0;
  int ret;
  for (int i = 0; i &lt; 21; i++) {
      if ((ret = read(sfd_client, (char *) &amp;num, sizeof(num))) == -1) {
          perror("read");
          exit(1);
      }
      printf("number = %d  = %ld  ret = %d\n", i, num, ret);
  }
  </code></pre>
  
  <p>Client: </p>
  
  <pre><code>for (int i = 0; i &lt; 21; i++) {
      if (write(sockfd_client, &amp;temp[i], sizeof(long int)) == -1) {
          exit(1);
      }
  }
  </code></pre>
  
  <p>I noticed that after calling the read the return value is exactly 8, which means that 8 bytes were read; yet the data is always 0. I don't understand what I am doing wrong. Also I was looking at various functions, and all cater to unsigned numbers but not signed (ntoh and hton family).</p>
  
  <p>NOTE: Also I noticed that the first read() is 8 bytes, but the following ones are only 1 byte.</p>
  
  <p>Whats the best way I can transmit all these numbers? (Also I noticed that the for loop refuses to quit if I have the read statement in there.)</p>
  
  <p>Solution (The problem was the fact that the read was returning less bytes than required, This function solved it)</p>
  
  <pre><code>void read_long(int sockfd_client, char *num) {
      unsigned int size = sizeof(long int);
      int rlen = 0;
      int ret;
  
      while (rlen &lt; size) {
          if ((ret = read(sockfd_client, (num + rlen), size - rlen)) == -1) {
              perror("read_long");
              exit(1);
          }
  
          if (ret == 0) {
              perror("socket closed before consumption");
              exit(1);
          }
          rlen += ret;
      }
  }
  </code></pre>