Pregunta

I have the following client code that connects to a server:

#include<stdio.h> //printf
#include<string.h>    //strlen
#include<sys/socket.h>    //socket
#include<arpa/inet.h> //inet_addr

int main(int argc , char *argv[])
{
    int sock;
    struct sockaddr_in server;
    char message[1024], server_reply[2000];

    //Create socket
    sock = socket(AF_INET , SOCK_STREAM , 0);
    if (sock == -1)
    {
        printf("Could not create socket");
    }
    puts("Socket created");

    server.sin_addr.s_addr = inet_addr("127.0.0.1");
    server.sin_family = AF_INET;
    server.sin_port = htons( 8888 );

    //Connect to remote server
    if (connect(sock , (struct sockaddr *)&server , sizeof(server)) < 0)
    {
        perror("connect failed. Error");
        return 1;
    }

    puts("Connected\n");
    puts("Bienvenido al Chatroom, puedes empezar a escribir en la sala!");

    //keep communicating with server
    while(1)
    {

        printf("Enter message: ");
    fgets(message, 1024 ,stdin);
        //scanf("%s" , message);

        //Send some data
        if( send(sock , message , 1024 , 0) < 0)
        {
            puts("Send failed");
            return 1;
        }

        //Receive a reply from the server
        if( recv(sock , server_reply ,2000, 0) < 0)
        {
            puts("recv failed");
            break;
        }

    puts(server_reply);


    }

    close(sock);
    return 0;
}

Whenever I send a message through the socket, the server echoes the message back to the client. It works most of the times, but after a few messages iterations, the echo starts to fail. Here's an example of how it fails.

Enter Message: Hi there! Server reply: Hi there!

Enter Message: Where are you from? Server reply: Where are you from?

Enter Message: Nice! Server Reply: Nice! are you from?

Enter Message: And you ? Server Replay: And you ? you from?


So it seems somehow i keep garbage in the stdout buffer or something like that. I don't really know what it is. Is there anything wrong with the code or just a simple fix up to do with fputs ? (Maybe it has something to do with message and server_reply array's size).

¿Fue útil?

Solución

just before fgets(message, 1024 ,stdin); add memset(message, 0, 1024);

the same should be done for server_reply:

memset(server_reply, 0, 2000);
if( recv(sock , server_reply ,2000, 0) < 0)

and for server-side too

to read more: Null-terminated string

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top