Home > database >  why I cant send and recv integers in a loop correctly
why I cant send and recv integers in a loop correctly

Time:07-08

I have the following code in my server program:

void sendAccounts(const Database& data, int socket, int32_t user)
{
   std::vector<int32_t> accounts = data.getUsersAccounts(user);
   uint16_t number = accounts.size();
   number = htons(number);
   send(socket, reinterpret_cast<char*>(&number), sizeof(number), 0);
   for (size_t i = 0; i < accounts.size();   i)
   {    
        std::cout << accounts[i] << std::endl;
        int32_t account = htonl(accounts[i]);
        send(socket, reinterpret_cast<char*>(&account), sizeof(account), 0);
   }
}

And the following code in my client program:

std::vector<int32_t> getAccounts(int socket)
{
    uint16_t n_accounts;
    std::vector<int32_t> accounts;
    recv(socket, reinterpret_cast<char*>(&n_accounts), sizeof(n_accounts), 0);
    n_accounts = ntohs(n_accounts);
    for (uint16_t i = 0; i < n_accounts;   i)
    {
        int32_t account = 0;
        recv(socket, reinterpret_cast<char*>(account), sizeof(account), 0);
        account = ntohl(account);
        accounts.push_back(account);
    }
    return accounts;
}

For some reason the client correctly receives the number of accounts but unable to receive account numbers, each recv returns -1, when I check errno it is equal to 0. What can be wrong?

CodePudding user response:

In the recv() loop, you are casting the value of account, which is always 0, thus producing a null pointer. This is the main reason why recv() is failing.

You need to instead cast the address of account (just as you did with n_accounts above the loop). So, change this:

reinterpret_cast<char*>(account)

To this:

reinterpret_cast<char*>(&account)

That being said, on most platforms, send() and recv() take void* pointers, so you don't actually need to use reinterpret_cast at all on those platforms.

Since you mention errno, I assume you are not running this code on Windows. If you were, then send()/recv() do take char* pointers and thus would need the casts (and you should be using WSAGetLastError() instead of errno).

  • Related