0

I use socket client to send http request, all works fine, but some time, some host return strange/wrong data. for example:

HTTP/1.1 200 OK
Date: Tue, 12 May 2020 23:19:07 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.6
X-Powered-By: PHP/7.2.6
Transfer-Encoding: chunked
Content-Type: application/json

2322
{"content_type":"application/json","response":{"datetime":"2020-05-13 02:19:07","result":0,"signature":""}}

0

correct data is:

HTTP/1.1 200 OK
Date: Tue, 12 May 2020 23:19:07 GMT
Server: Apache/2.4.33 (Win32) OpenSSL/1.1.0h PHP/7.2.6
X-Powered-By: PHP/7.2.6
Transfer-Encoding: chunked
Content-Type: application/json


{"content_type":"application/json","response":{"datetime":"2020-05-13 02:19:07","result":0,"signature":""}}

i get it if use POSTMAN. to recive data from host I use code:

int len = 512;
char buf_new[1000000];
buf_new[0] = '\0';
do {
    len = recv(socket, buf_new, 512, 0);
    buf_new[len] = 0;

    Result += buf_new;
    buf_new[0] = '\0';
} while (len > 0);

If anyone know what is problem - please help, thanks!

  • https://stackoverflow.com/questions/47975612/c-nonblocking-sockets-wait-for-all-recv-data – Kuba May 12 '20 at 23:32
  • `char buf_new[1000000];` just threw 1000000 bytes onto the stack. You might not have 1000000 bytes available. It looks like you only need 512, so you might as well scale back the size of that buffer. – user4581301 May 12 '20 at 23:46
  • i saw it, it's not my case.... – Николай Деменков May 12 '20 at 23:46
  • i try change 1000000 to 512, but it was the same problem – Николай Деменков May 12 '20 at 23:58
  • What you are getting is correct. It is in chunked transfer mode, with two chunks of 2322 and then 0 bytes, the latter indicating end of stream, and you have no code to do the unchunking. The 'correct' data you show must have come from a client that handled unchunkng for you. – user207421 May 13 '20 at 00:22
  • Your reading loop is not taking the `Transfer-Encoding: chunked` into account at all. That is what the "strange/wrong data" actually belongs to. See [RFC 2616 Section 3.6.1](https://tools.ietf.org/html/rfc2616#section-3.6.1) and [RFC 7230 Section 4.1](https://tools.ietf.org/html/rfc7230#section-4.1) for details. What you are doing is not the correct way to read an HTTP response. See [this pseudo-code](https://stackoverflow.com/a/16247097/65863) for the correct logic you need to use. – Remy Lebeau May 13 '20 at 00:34

0 Answers0