开发者

C Winsock programming: input garbage

开发者 https://www.devze.com 2022-12-16 06:08 出处:网络
I\'m programming a very simple socket server following this sample code. The server is up and running and I can connect to it via telnet (using Putty, actually). Whenever a new connection is received,

I'm programming a very simple socket server following this sample code. The server is up and running and I can connect to it via telnet (using Putty, actually). Whenever a new connection is received, I spawn a new thread that is the following code:

DWORD WINAPI receive_cmds(LPVOID lpParam) 
{
      char outbuffer[100];
      outbuffer[0] = '\0';
      char inbuffer[100];
      inb开发者_如何学Pythonuffer[0] = '\0';
      int res;
      SOCKET current_client = (SOCKET)lpParam;

      while (1) {           
          res = recv(current_client, inbuffer, sizeof inbuffer - 1, 0);
          if (res > 0) {
              inbuffer[res] = '\0';
              printf("Got '%s'\n", inbuffer);
          }              
          Sleep(10);

          if (res == 0) {
             closesocket(current_client);
             ExitThread(0);             
          }                          

          //printf("%s\n", inbuffer); 
          strcpy(inbuffer, "");
      }
}

As soon as I connect it prints this gibberish:

C Winsock programming: input garbage

If i input "hello" and then "stackoverflow" in the client, this is what I get:

C Winsock programming: input garbage

Even if I declared explicitly the end of line '\0', it seems to take much more of the line, plus I don't know why it prints the input two times, the second being the first one minus the first one or two characters.

Any help on understanding what is going on? Thanks in advance.

EDIT: edited accordingly to what suggested by unwind


You should do better error-checking, and more sensible buffer handling:

res = recv(current_client, inbuffer, sizeof(inbuffer), 0);

should be

res = recv(current_client, inbuffer, sizeof inbuffer - 1, 0);
if (res > 0)
{
  inbuffer[res] = '\0';
  printf("Got '%s'\n", inbuffer);
}

You need to leave space in the buffer for the terminator, so you can't use all of the buffer to receive data. And you should check for -1, and terminate the buffer to make it into a string before printing it as such.


I guess that recv() is returning "-1" (meaning error).

I'd have to see the rest of your code to guess why. Try testing for a return of -1 and then calling WSAGetLastError() to find out the reason for the error.

0

精彩评论

暂无评论...
验证码 换一张
取 消