Reputation: 927
I'm doing a chat server using sockets and thread in C, but I have different problem : - I'm not able to send a message to client using his nickname - I've got a problem sending a message and attach the client sender nickname Can you help me on this please ?
How I fix the nickname :
/* Asks for client nickname */
if (strcmp(clients_nick[client], "") == 0) {
write(fd, msg, strlen(msg) * sizeof(char));
int rc = read(fd, buf, BUFLEN);
if (rc > 0) {
/* Deleting the character \n */
buf[strlen(buf) - 1] = '\0';
snprintf(clients_nick[client], MAX_NICK_LENGTH - 1, "%s", buf);
}
}
How I send the message : void client_write_message ( char * msg, int client_sender, int client_receiver) { char * buffer; buffer = calloc(BUFLEN, sizeof(char));
snprintf(buffer, BUFLEN, "[%s", clients_nick[client_sender]);
buffer[strlen(clients_nick[client_sender])] = ']';
snprintf(buffer, BUFLEN, " %s", msg);
write(clients[client_receiver], msg, strlen(msg) * sizeof(char));
buffer[0] = '\0';
free(buffer);
}
Upvotes: 0
Views: 757
Reputation: 121961
This is incorrect:
buf[strlen(buf) - 1] = '\0';
as read()
does not append a null terminator, upon which strlen()
depends. The value returned by strlen()
is unknown and may result in accessing out of bounds on buf
. Remove the null terminator assignment and replace with:
if (rc > 0)
{
snprintf(clients_nick[client], MAX_NICK_LENGTH - 1, "%.*s", rc, buf);
}
The result of read()
is the number of characters read, stored in rc
in the posted code, and the format specifier %.*s
uses a length and buffer and does not require the buffer to be null terminated.
Upvotes: 2