title: Send struct over socket in C
body: <p>I am developing a client/server program and my client has to send messages to the server.  </p>
  
  <p><strong>Sample message C structure</strong>:  </p>
  
  <pre><code>struct Registration
  {
  char multicastGroup[24];
  pid_t clientPid;
  };
  </code></pre>
  
  <p><strong>Client code snippet to serialize struct</strong>  </p>
  
  <pre><code>struct Registration regn ;
  regn.clientPid = getpid();
  strcpy(regn.multicastGroup, "226.1.1.1");
  
  printf("PID:%d\n", regn.clientPid);        
  printf("MG:%s\n", regn.multicastGroup);
  printf("Size:%d\n", sizeof(regn));           //Size is 28
  
  data = (unsigned char*)malloc(sizeof(regn));
  memcpy(data, &amp;regn, sizeof(regn));
  printf("Size:%d\n", sizeof(data));           //Size is 4.  
  </code></pre>
  
  <p><strong>Server code to de-serialize data</strong>  </p>
  
  <pre><code>if(recvfrom(sd, recvBuf, recvBufSize, 0, (struct sockaddr*)&amp;clientAddr, &amp;len) &lt; 0)
  {
         printf("Error receiving message from client\n");
  }
  else
  {
         printf("Message received:%s\n", recvBuf);
         printf("Size :%d\n", strlen(recvBuf));
         memcpy(&amp;regn, recvBuf, sizeof(regn));
         printf("PID:%d\n", regn.clientPid);
         printf("MG:%s\n", regn.multicastGroup);
  }
  </code></pre>
  
  <p>After copying the struct to <code>unsigned char *</code>, the size of the array is only 4.<br>
  Why is data not fully copied to the array?  </p>
  
  <p>The server is not able to reconstruct the struct from the char array.<br>
  Please let me know what am I doing wrong.</p>