Trevor,
Disclaimer: Might work. This is somewhere I am also stuck at this time with a similar problem.
What you seek is called "marshalling the data".
On Mon, 2005-09-05 at 10:18, Trevor Warren wrote:
On the server i have a struct defined as:
struct sendbuff { int count; char toprint[10000]; };
For ease of use let the structure be: typedef struct sendbuff { int count; char *toprint; } SENDBUFF; .................. { SENDBUFF *sbuf = malloc (sizeof(SENDBUF); sbuf->count = 999; sbuf->toprint = malloc(strlen("This is Cool Stuff!")); strcpy (sbuf->toprint, "This is cool Stuff!");
// Now { char *databuf; int bufsize = 0, buflen = 0; bufsize = sizeof(int) + strlen(sbuf->toprint) + 1; databuf = malloc (bufsize); memset (databuf, 0, bufsize); memcpy(databuf, &(sbuf->count), sizeof(int)); buflen = sizeof(int); memcpy(databuf + buflen, sbuf->toprint, strlen(sbuf->toprint) + 1); //buflen += strlen(sbuf->toprint) + 1;
// Now do the sending to the client socket // send (client_sock, databuf, bufsize, 0); ....................... }
Done on the server:
My objective is to pack this buffer across the n/w and recv it on the client. count is a simple counter which i am usign to keep track of the lost/unordered packets is any. My recv system call on the client is as follows. mybuff on the client has been declared of type struct sendbuff.
Declare mybuff as char *.
char *mybuff;
while(1) //Beggining of While { while(bytesrcvd<sizeof(mybuff)) {
if ((numbytes=recv(sockfd, (char *)mybuff, sizeof(mybuff), 0)) == -1) { perror("recv"); exit(1); } bytesrcvd=numbytes+bytesrcvd; }
Now over here we retrieve the struct members from mybuff.
{ SENDBUFF *recvdstuff; recvdstuff->count = *((int *)mybuff; recvdstuff->toprint = mybuff + sizeof(int);
printf("recvdstuff->count is: %d\n", recvdstuff->count); printf("recvdstuff->toprint is: %s\n", recvdstuff->toprint); }
This should work, with a little tweaking to suit your needs. You could change recvdstuff not to be a pointer.
Could somebody point me to handling a case as follows:
typedef struct test_struct { int s_id; char *doc_id; } TEST_STRUCT;
sendbuff in my case is **ts (where ts is TEST_STRUCT **ts).
Thanks in Advance, Animesh