Min Kim
Min Kim

Reputation: 113

Send a struct using socket over http

I want to transfer a struct (has data and ID etc.) over http using send() and recv(). Over TCP the following two lines works perfectly.

Client: send(sock, (char *)&StructToSend, sizeof(StructToSend), 0);
Server: recv(sock, (char *)&StructToRecv,  sizeof(StructToRecv),0); 

But when over HTTP, the StructToRecv gets only two bytes messy code like this: ÈÈ

    ////Client code: send over http
    int length = 0;
    char header[4096];
    char tmp_name[80];
    memset(tmp_name, 0, sizeof(tmp_name));
    strcat_s(tmp_name, "tmp.txt");

    length  = (sizeof(SendStruct)+strlen(tmp_name)+ 287);

    sprintf_s(header, "POST /%s/index.html HTTP/1.1\r\n", sub_dir;
    sprintf_s(header, "%sHost: %s \r\n", header , szIP);
    sprintf_s(header, "%sUser-Agent: Mozilla/5.0 (Windows NT 6.1; rv:32.0) Gecko/20100101 Firefox/32.0\r\n", header);
    sprintf_s(header, "%sAccept: text/html;q=0.9,*/*;q=0.8\r\n", header);
    sprintf_s(header, "%sAccept-Language: en-US,en;q=0.5\r\n", header);
    sprintf_s(header, "%sAccept-Encoding: gzip, deflate\r\n", header);
    sprintf_s(header, "%sConnection: Keep-Alive\r\n", header);
    sprintf_s(header, "%sContent-Type: multipart/form-data; boundary=-----------------------------26774670897926\r\n", header);
    sprintf_s(header, "%sContent-Length: %d\r\n", header, length );
    sprintf_s(header, "%s\r\n", header);  //blank line
    sprintf_s(header, "%s-------------------------------26774670897926\r\n", header);
    sprintf_s(header, "%sContent-Disposition: form-data; name=\"file\"; filename=\"%s\"\r\n", header, tmp_name);
    sprintf_s(header, "%sContent-Type: text/plain\r\n", header);
    sprintf_s(header, "%s\r\n", header);  //blank line
    sprintf_s(header, "%s%s\r\n", header,  (char *)&StructToSend );
    sprintf_s(header, "%s-------------------------------26774670897926\r\n", header);
    sprintf_s(header, "%sContent-Disposition: form-data; name=\"submit\"\r\n", header);
    sprintf_s(header, "%s\r\n", header);
    sprintf_s(header, "%sSubmit\r\n\r\n", header);
    sprintf_s(header, "%s-------------------------------26774670897926--\r\n\r\n\0", header);      

    send(sock, header, sizeof(header), 0);


    ////Server code : recv over http 
    char http_data[4096] = { '\0' };
    ZeroMemory( http_data, sizeof( http_data));
    recv(sock,  http_data,  4096, 0);

Upvotes: 1

Views: 285

Answers (1)

Steffen Ullrich
Steffen Ullrich

Reputation: 123380

sprintf_s(header, "%s%s\r\n", header,  (char *)&StructToSend );

You are using sprintf(...%s..). This means the data you give are treated as a char string terminated with \0, i.e. only data up to the first \0 will be included.

Upvotes: 3

Related Questions