AlvaroAV
AlvaroAV

Reputation: 10553

C sockets: Echo server bad reply

I've read as many questions as I've found, still I have my problem....

I have a very sample client/server socket:

I send the message from client to server without problems, but when I send back the message I'm allways getting weird characters

Note: I'm adding the '\0' character to the received string

Client code

//... socket initialization and other code
write(sockfd, msg, strlen(msg));    
printf("Message sent ! \n"); 

// Listen for reply
listen(sockfd, 5);
struct_size = sizeof(con_addr);
serverfd = accept(sockfd, (struct sockaddr*)&con_addr, &struct_size);

// Read message
bytes_read = read(serverfd, server_reply, 100);
server_reply[bytes_read] = '\0';
printf("Server response: %s \n", server_reply);

// Close socket
close(sockfd);
close(serverfd);
printf("Socket closed ! \n");     

Server Code

//... socket initialization, bind and other code
struct_size = sizeof(con_addr);
if( (clientfd = accept(sockfd, (struct sockaddr*)&con_addr, &struct_size)) < 0 ){
    perror("Could not accept connection. Error: ");
    return 1;
}

// Read message
bytes_read = read(clientfd, client_message, 100);
client_message[bytes_read] = '\0';

printf("Message received: %s \n", client_message);      
// Send message back
n = write(clientfd, client_message , strlen(client_message));    

I'm getting things like this:

Server response: �V��i�8�y�
Server response: ��ƿi�8�{� 

Upvotes: 2

Views: 592

Answers (1)

Nikolai Fetissov
Nikolai Fetissov

Reputation: 84159

You are confused on how TCP sockets work:

It looks like currently you are attempting to connect/accept on both sides.

Other notes:

  • Always check return values of system calls - -1 is an indication of an error, then inspect errno(3) for the actual problem (strerror(3) is useful here).
  • Do not assume the data is ASCII, so not use strlen(3) on socket input, use return value of read(2).

Upvotes: 4

Related Questions