简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM