recv function from winsock.h, i don't understand how it works

57 Views Asked by At

I'm a beginner. The function requests the following parameters:

int recv(
  [in]  SOCKET s,
  [out] char   *buf,
  [in]  int    len,
  [in]  int    flags
);

The second parameter requests me to pass the address of a buffer, but in a video i'm watching, the guy passes the buffer by value, and as far as i know by doing this the function won't be able to modify the buffer, but for some reason it accepts the parameter anyway. Why?

This is the video: https://www.youtube.com/watch?v=VlUO6ERf1TQ&t=361s

This is the piece of code he writes:

int bytes = 0;
    while (true)
    {
        //Accept client request
        new_wsocket = accept(wsocket, (SOCKADDR *)&server, &server_len);
        if (new_wsocket == INVALID_SOCKET)
        {
            std::cout << "The socket is invalid";
        }

        //Read request
        char buff[30720] = { 0 };
        bytes = recv(new_wsocket, buff, BUFFER_SIZE, 0);
    }

1

There are 1 best solutions below

1
Remy Lebeau On

In various contexts (including when passed as a function parameter), a C-style array that is referred to by just its name alone will decay into a pointer to its 1st element.

See: What is array-to-pointer conversion aka. decay?

So, in this situation, this code:

char buff[30720] = { 0 };
bytes = recv(..., buff, ...);

Is functionally identical to this code:

char buff[30720] = { 0 };
bytes = recv(..., &buff[0], ...);

On a side note: you have a BUFFER_SIZE constant defined, which you are passing to recv() as the size of the array that it reads into, but you are not using that same constant when declaring the array itself. To help keep things consistent, you should either:

  • declare the array using the constant:
char buff[BUFFER_SIZE] = { 0 };
  • use sizeof() instead of the constant:
bytes = recv(..., buff, sizeof(buff), ...);