madziikoy
madziikoy

Reputation: 1497

C++ Server not displaying the packet

I'm making a server in C++ winsock
Right now I'm trying to debug and see what packet the client sent.

Here is my code

int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;

(...)

iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
    cout << "The packet is: " << hex << recvbuf << endl;

But on the console when the client has connected the display is just:

The packet is:

Nothing is displayed. What am I missing?

If I do:

int iSendResult;
char recvbuf[DEFAULT_BUFLEN];
int recvbuflen = DEFAULT_BUFLEN;

(...)

iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
    cout << "The packet size: " << iResult << endl;
//result is "The packet size: 10"

Now I want to see what that packet is.


UPDATE

I tried this:

iResult = recv(ClientSocket, recvbuf, recvbuflen, 0);
if (iResult > 0) {
    string packet = recvbuf;
    cout << "The packet is: " << packet.c_str() << endl;

Still no strings returned. just "The packet is: "

Upvotes: 1

Views: 110

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84151

The bytes you receive in that buffer might be non-printable, and might be not zero-terminated. Print them as integers, say, with hexadecimal format, in a loop from 0 to iResult - 1.

Edit 0:

The important part is that you need to print exact number of bytes. Something as simple as the following would do (unsigned char to avoid sign-extension of values larger then 127):

unsigned char buf[BSIZE];
// ... get data of size iResult
for ( int i = 0; i < iResult; i++ ) {
    printf( "%02x ", buf[i] );
}
printf( "\n" );

Upvotes: 1

Related Questions