PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, October 22, 2022

[FIXED] why I cant send and recv integers in a loop correctly

 October 22, 2022     c++, sockets     No comments   

Issue

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?


Solution

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).



Answered By - Remy Lebeau
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing