0

I need to receive "multipart/form-data" upload request which contains many binary files. From the tutorials I read, this is the way I came up with to instruct the server how to know when to stop receiving HTTP Request packets:

while (true)
{
#ifdef _WIN32
    u_long arg;
    if (ioctlsocket(socket, FIONREAD, &arg) == SOCKET_ERROR)
        throw std::exception("ioctlsocket");
#else
    int arg;
    if (ioctl(socket, FIONREAD, &arg) == -1) throw std::exception("ioctl");
#endif
    else if (arg == 0) break;

    char buf[1024];
    auto received = recv(socket, buf, 1024, 0);
#ifdef _WIN32
    if (received == SOCKET_ERROR) throw std::exception("recv");
#else
    if (received == -1) throw std::exception("recv");
#endif
    else if (received == 0) break;
    else
    {
        // work with the buffer
    }
}

The current solution isn't reliable, for example it doesn't have a timeout value. Are there any better ways to receive HTTP Requests?

MiP
  • 5,846
  • 3
  • 26
  • 41
  • 3
    Yes, actually parsing the HTTP request and handling the data based on that. Chunked, content-length, keepalives etc – Sami Kuhmonen Jul 31 '17 at 03:57
  • @SamiKuhmonen But a HTTP request doesn't need a `Content-Length` header, how can I parse the request without knowing its length? https://stackoverflow.com/a/15995101/7821462 – MiP Jul 31 '17 at 04:02
  • That's where chunked encoding etc comes in. If it's a POST request there will be the information needed to know when it ends. That's how HTTP works, there is no guessing – Sami Kuhmonen Jul 31 '17 at 04:03
  • 1
    The answer you linked to is about responses, not requests. Requests can't be delimited by end of stream, otherwise you can't send the response, so they have to have either Content-length or chunked transfer encoding. – user207421 Jul 31 '17 at 05:22
  • 1
    MIME `multipart/` types are self-delimiting, so technically you do not NEED `Content-Length` or `Transfer-Encoding: chunked`, you can just parse the data until you reach the closing boundary line. See [RFC 2616 Section 4.4 Message Length](https://tools.ietf.org/html/rfc2616#section-4.4) (which mentions only `multipart/byteranges`, but applies to any `multipart/` type). However, [RFC 7230 Section 3.3.3 Message Body Length](https://tools.ietf.org/html/rfc7230#section-3.3.3) invalidates that approach by ignoring MIME altogether, thus requiring `Content-Length` or `Transfer-Encoding: chunked`. – Remy Lebeau Jul 31 '17 at 19:13

0 Answers0