Passing a structure over a TCP socket in C

I am writing a small client server application in C.

On the client side , I have one structure, for example

#pragma pack(1)   // this helps to avoid serialization while sending over network. 
typedef struct _viewBoxClient_Info
{
  unsigned long viewBoxID;
  int bRT_flag;
  int nFrameNum;
  char frameData[1000];   
}viewBoxClient_info_send ;
#pragma pack(0)   // turn packing off 

and filling in the variable as,

struct _viewBoxClient_Info client_info;
client_info.bRT_flag= 10;/*0 for false, 1 for true*/
client_info.viewBoxID=10000;
memcpy(client_info.frameData,buf,sizeof(client_info.frameData)); //char buf[] data is "is 1st line"
client_info.nFrameNum=1;

and sending to the server using the following function

send(sock, (char *)&client_info, bytesRead, 0);

On the server side, I have one structure (same as the structure on the client side),

#pragma pack(1)   // this helps to avoid serialization while sending over network.
typedef struct _lclviewBoxClient_Info
{
 unsigned long viewBoxID;
 int bRT_flag;
 int nFrameNum;
 char frameData[1000];
}viewBoxClient_info_receive ;
#pragma pack(0)   // turn packing off

and receive a message and print on the screen as,

viewBoxClient_info_receive lcl_viewBox;
ssize_t bytesReceived = recv( *nfd, &lcl_viewBox, sizeof(struct _lclviewBoxClient_Info), 0);
printf("\nlcl_viewBox.bRT_flag:%d\n",lcl_viewBox.bRT_flag);
printf("lcl_viewBox.nFrameNum:%d\n",lcl_viewBox.nFrameNum);
printf("lcl_viewBox.frameData:%s\n",lcl_viewBox.frameData);

O / p on the server screen,

 lcl_viewBox.bRT_flag:1
 lcl_viewBox.nFrameNum:1936287860
 lcl_viewBox.frameData: is 1st line

I do not know what exactly is happening on my server side. I send 10 for bRT_flag from the client and get 1 on the server. Also sending nFrameNum = 1 from the client and receiving as nFrameNum: 1936287860 on the server. frameData also on the client side I send "This is the 1st line", and on the server only "1st line". Has anyone helped with this to get rid of this problem?

,

+3
3

:

send(sock, (char *)&client_info, bytesRead, 0);

:

send(sock, (char *)&client_info, sizeof( client_info ), 0);

send() , , recv() - , recv .

+2

, .

( ), ( #pragma pack), , "int" .

, ​​ Google Protocol Buffers, . , htonl , uint32_t ..

, writeClientStruct (int sock, struct client_struct *), , .

+2

, "unsigned long". ( , - 32- 64-).

:

  • bRT_flag 32 nFrameNum
  • nFrameNum, 32 frameData (1936287860 → 0x73696874 → "siht" → "this")

A trivial check for this would be to check sizeof (struct) or sizeof (unsigned long) to see if they match.

Please see Mike Weller's post on how to fix this.

0
source

All Articles