简体   繁体   中英

Passing structure over a Socket from client to server

I need to code for uploading a file from client to server.

In client side, i have declared a structure,

typedef struct upload_file
{
 char *filename;
 char *filebuffer;
}upload_file;

I am getting filename from command line argument.

In main function, I am assigning the file name with structure variable.

upload_file.filename = argv[1];

Then I am reading the file content, putting into a buffer & copying that to structure's buffer value.

strcpy(upld.buffer,tmp); //tmp is a buffer which will contain the file content

After that I am writing the structure into socket as follows,

 write(sd, &upld, sizeof(upld));

This part is fine with the client side. In the server side if I read the whole structure & how do i separate the file content & file name?

Also , the buffer value (ie file content ) from client side is malloced & could it be available to server side?

How do to this?

Thanks in advance.

Passing a structure with pointers in it is useless. The pointers themselves will be sent across but not the things they point to.

What you need to do is marshal the data for transmission, something which the various RPC mechanisms (OPC, DCE, etc) do quite well.

If you can't use an established method like that, it's basically a matter of going through the structure element by element, copying the targets into a destination buffer.

For example, with the structure:

struct person {
    int age;
    char *name;
    char *addr;
} p;

you could do something like:

msgbuff = outbuff = malloc (
    sizeof (int) +
    strlen (p.name) + 1 +
    strlen (p.addr) + 1
    );
if (msgbuff != NULL) {
    *((int*)outbuff) = p.age;  outbuf += sizeof (p.age);
    strcpy (outbuff, p.name) ; outbuf += strlen (p.name) + 1;
    strcpy (outbuff, p.addr) ; outbuf += strlen (p.addr) + 1;
    // Send msgbuff
    free (msgbuff);
} else {
    // Some error condition.
}

Note that an int is transferred directly since it's in the structure. For the character pointers (C strings), you have to get at the target of the pointer rather than the pointer itself.

Essentially, you transform:

p:  age  (46)
    name (0x11111111)  -->  0x11111111: "paxdiablo"
    addr (0x22222222)  -->  0x22222222: "Circle 9, Hades"
   |--------------------|-------------------------------|
    structure memory <- | -> other memory

into:

msgbuff (0x88888888) -> {age}{"paxdiablo"}{"Circle 9, Hades"}

This complicates the process a little since you also have to unmarshal at the other end, and you'll need to watch out for system that have different sized int types. But that's basically how it's done.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM