Devember: Nickname command

This post is part of the Devember collection, useful for the study of the Socket API.

Devember: Nickname command

After transforming the server in a chat room, I thought it was a good idea to add a command to set your nickname. So, when a client connects, the server expects to receive a message starting with /nickname followed by the actual nickname:

#define MAXNICK 32
// ...
char nicknames[FD_SETSIZE][MAXNICK];
// Processing the ith client
if (nicknames[i][0] == 0) {
    if (strncmp(buff, "/nickname", 9) == 0) {
        sscanf(buff, "/nickname %s\n", nicknames[i]);
        sprintf(buff, "%s has joined the chat\n", nicknames[i]);
    } else {
        sprintf(buff, "Error, expecting /nickname \n");
        exso_writen(client[i], buff, strlen(buff));

If the nickname is already set, it is added to the beginning of the message to be broadcast:

char temp[MAXLINE];
sprintf(temp, "%s: %s", nicknames[i], buff);
sprintf(buff, "%s", temp);
// ...
for (i = 0; i < FD_SETSIZE; i++) {
    if (sockfd == client[i] || client[i] == -1) {
    if (exso_writen(client[i], buff, strlen(buff)) < 0) {

Finally, when a client logs off, the nickname will reset:

// If there are no characters to read
if (n == 0) {
    FD_CLR(sockfd, &allset);
    client[i] = -1;
    bzero(nicknames[i], MAXNICK);

The complete code can be found on this repository.

15 December 2015