user2837961
user2837961

Reputation: 1555

Socket recv in c++

My code is as below

char *inBuffer = new char[5];
int recvReturn = recv(Socket, inBuffer, sizeof(inBuffer) - 1, 0);
if (recvReturn <= 0)
{
    m_manager->log("Socket receive error",HIGH_IMPORTANCE);
}
else
{
    std::stringstream ss2;
    ss2<<std::hex;
    for(int i(0);i<5;++i)
      ss2<<(int)inBuffer[i] << ' ';
    m_manager->log(ss2.str(),HIGH_IMPORTANCE);
}

The result in my log is

1 1 6 0 0

The values on 1 1 6 are correct but 0 0 is wrong. Instead of 0 0 I expect 8 9. Is there something wrong in the code?

Upvotes: 0

Views: 112

Answers (1)

Serge Ballesta
Serge Ballesta

Reputation: 149155

I can see 2 problems in your code.

  • you print 5 characters without ensuring you recieved at least 5. You should display recvBuffer and/or limit the number of chars written to that.
  • if you received bytes with value 1, 6, 8, 9 they are not printable characters. The (ASCII) code of 0 is 0x30 or 48. So ss2.str could be weird as a printable string.

Upvotes: 1

Related Questions