SystemsArticle10 min read

Writing a chat server from scratch: sockets, poll() and IRC

ft_irc: an IRC server in C++98 that serves many clients from one thread and one poll() loop, and works with real IRC clients. How it works, with our code, and a live session between two clients.

By Abdeljalil El HidaouiSource code
On this page

Every chat app you use sits on top of the same problem: one server, many people connected at once, each of them sending bytes whenever they like. ft_irc solves it from the bottom up, in C++98, with raw sockets and a single event loop: no threads, no fork(), no networking library.

We built it in a team of two, as a 42 project. It speaks enough of the IRC protocol for real clients such as irssi, WeeChat and HexChat to connect and chat. This article explains how, with code from the repository, and ends with a live session where two clients talk through a simulated copy of the server.

What IRC is

IRC (Internet Relay Chat) dates from 1988 and is refreshingly simple: clients open a TCP connection and send lines of text, each ending with \r\n. The server relays messages to other users directly, or through channels, chat rooms whose names start with #.

NICK alice
JOIN #general
PRIVMSG #general :hello everyone!

The server answers with numeric replies: 001 welcomes you, 433 means the nickname is taken, 482 means you aren't a channel operator. Clients understand these codes, which is why getting them exactly right matters.

thread, one poll() loop
1
no external libraries
C++98
commands, 5 channel modes
12
real IRC clients it works with
4

Opening a socket

A server starts by asking the operating system for a socket, binding it to a port and listening. Two options matter: SO_REUSEADDR, so the server can restart on the same port right away, and O_NONBLOCK, so no call will ever freeze the whole program waiting for one client.

src/Creat_Server.cppView on GitHub
this->setServer_fd(socket(AF_INET, SOCK_STREAM, 0));
if (this->getServer_fd() == -1)
{
    std::cerr << "Socket failed" << std::endl;
    return false;
}
int opt = 1;
struct sockaddr_in address;
address.sin_family = AF_INET;
address.sin_addr.s_addr = INADDR_ANY;
address.sin_port = htons(this->getPort());
this->setAddress(address);
if (setsockopt(this->getServer_fd(), SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) < 0)
{
    std::cerr << "Setsockopt failed" << std::endl;
    close(this->getServer_fd());
    return false;
}
if (fcntl(this->getServer_fd(), F_SETFL, O_NONBLOCK) < 0)
{
    std::cerr << "Fcntl failed" << std::endl;
    close(this->getServer_fd());
    return false;
}
if (bind(this->getServer_fd(), reinterpret_cast<struct sockaddr *>(&address), sizeof(address)) < 0)
{
    std::cerr << "Bind failed" << std::endl;
    close(this->getServer_fd());
    return false;
}
if (listen(this->getServer_fd(), 5000) < 0)
{
    std::cerr << "Listen failed" << std::endl;
    close(this->getServer_fd());
    return false;
}
return true;

Each new connection gets its own socket from accept(), which is made non-blocking too and wrapped in a Client object, stored by its file descriptor:

src/Creat_Server.cppView on GitHub
int client_fd = accept(this->getServer_fd(), (struct sockaddr *)&client_address, &client_address_size);
if (client_fd < 0)
{
    std::cout << "Accept failed" << std::endl;
    return -1;
}
if(fcntl(client_fd, F_SETFL, O_NONBLOCK) < 0)
{
    std::cerr << "Fcntl failed" << std::endl;
    close(client_fd);
    return -1;
}
this->addClient(client_fd, new Client(client_fd));

One loop for everyone

With many clients, the naive approach is to wait for each one in turn, but recv() on a quiet client would block everyone else. The usual fixes are one thread per client, or I/O multiplexing: ask the kernel “which of these sockets have something for me right now?” and only touch those. That is what poll() does, and the subject requires exactly one call to it.

src/Creat_Server.cppView on GitHub
void Server::runServer(bool &close_ser)
{
    std::vector<pollfd> fds;

    fds.push_back(pollfd());
    fds.back().fd = this->getServer_fd();
    fds.back().events = POLLIN;
    while (!close_ser)
    {
        int ready = poll(&fds[0], fds.size(), 0);
        if (ready == -1)
        {
            this->close_all();
            break;
        }
        for (size_t i = 0; i < fds.size(); ++i)
        {
            if (fds[i].revents & POLLIN)
            {
                if (fds[i].fd == this->getServer_fd())
                {
                    int client_fd = this->accept_client();
                    if (client_fd > 0)
                    {
                        fds.push_back(pollfd());
                        fds.back().fd = client_fd;
                        fds.back().events = POLLIN;
                    }
                    else
                        continue;
                }
                else
                {
                    if (this->receve_msg(fds[i].fd) == -1)
                    {
                        fds.erase(fds.begin() + i);
                        i--;
                    }
                }
            }
        }
    }
    close(this->getServer_fd());
}

The listening socket sits in the same list as the clients. When it is readable, a new connection is waiting, so we accept() it and add its descriptor to the list. When a client socket is readable, it has sent data, or it has hung up.

One process, one thread and one poll() loop for every socket
One process and one thread: a single poll() loop watches every socket, keeps partial data per client until a full line arrives, and hands each command to a dispatcher.Open full size

TCP has no messages

Here is the trap that catches most first network programs: TCP is a stream of bytes, not of messages. A client can send PRIVMSG #42 :hello\r\n and the server can receive it as PRIV in one recv() and the rest in the next. With nc you can even trigger this by hand, by typing part of a command and pressing Ctrl+D.

So the server can't treat one recv() as one command. It keeps a buffer for each client, and only runs a command once a line ending has arrived:

src/Creat_Server.cppView on GitHub
char buffer[4096];
memset(buffer, 0, sizeof(buffer));
ssize_t bytesRead = recv(fd, buffer, sizeof(buffer) -1, 0);
if (bytesRead <= 0)
{
    std::cout << "[\033[31;1mINFO\033[0m] \033[31;1mClient Disconnected\033[0m" << std::endl;
    send(fd, "\033[31;1mYou are Disconnected 😞.\r\n\033[0m", 40, 0);
    this->remove_client_from_channels(fd);
    delete this->clients[fd];
    this->removeClient(fd);
    close(fd);
    return -1;
}
else
{
    buffer[bytesRead] = '\0';
    std::string str = buffer;
    size_t newline_pos = str.find_first_of("\r\n");
    if (newline_pos == std::string::npos)
    {
        this->clients[fd]->setStr(str);
        return 1;
    }
    else
    {
        std::string tmp = "";
        if (!this->clients[fd]->getStr().empty())
        {
        for (size_t j = 0; j < this->clients[fd]->getStr().size(); j++)
            tmp += this->clients[fd]->getStr()[j];
            this->clients[fd]->clearStr();
        }
        str = tmp + str;
        str  = update_str(str);

A recv() that returns 0 means the client closed the connection: the server removes them from every channel, frees their state and closes the socket.

Try a session

Here is a simulated copy of the server, with two clients. Type raw IRC commands or click the suggestions, or press play to watch a short scene. Tick “split into two TCP chunks” to see the per-client buffer at work.

Two clients, one server

Connect alice and bob, register them (PASS, NICK, USER), then create a channel, set modes and talk. Errors come back as red numeric replies.

alice@laptop: nc -C localhost 6667not connected
bob@laptop: nc -C localhost 6667not connected
ircservpoll() list:fd 3 · listening
  1. Waiting for events…

Simulated in your browser, following the repository's commands, rules and numeric replies. The server password is “secret”.

Registration

Before anything else, a client must register: send the server password with PASS, choose a nickname with NICK, then identify itself with USER. Until all three succeed, every other command is refused with 451, and NICK or USER without the right password first are refused too:

src/methodes.cppView on GitHub
if (!this->IsAuthorized(*c))
{
    if (words[0] == "PASS")
        cmdpass(words, c ,str);
    else if (words[0] == "NICK" && c->getPassword() ==  this->server_password)
        cmdknick(words, c );
    else if (words[0] == "USER" && c->getPassword() ==  this->server_password)
        cmduser(c, words , str);
    else
    {
        std::string nickMsg = ":" + this->get_hostnames() + " " + this->to_string(ERR_NOTREGISTERED) + " " + words[0] + " :You have not registered\r\n";
        send(c->getFd(), nickMsg.c_str(), nickMsg.length(), 0);
        return ;
    }
}

Once registered, sending PASS or USER again gets 462 You may not reregister, and an unknown command gets 421. Command names are case-insensitive, as in the RFC.

Channels and operators

A channel is created by the first person to join it, and that person becomes its operator. Operators control the channel with KICK, INVITE, TOPIC and five modes:

+i
Invite-only: you can join only after an operator invites you.
+t
Topic lock: only operators can change the topic.
+k <key>
Channel password: JOIN must include the key.
+o <nick>
Give operator rights to someone (−o takes them back).
+l <n>
User limit: at most n members.

Every JOIN goes through those rules before the user is added:

src/join.cppView on GitHub
// Check if the user is invited to the channel and the channel is invite only
if(it2 != channels.end() && it2->second->getInviteOnly() == true && !it2->second->is_invited_user(this->get_nickname(fd)))
{
    std::string msg = ":" + this->get_hostnames() + " 473 " + this->get_nickname(fd) + " " + channel_name + " :Cannot join channel (+i)\r\n";
    send(fd, msg.c_str(), msg.length(), 0);
    return (1);
}
// limit the number of channels a user can join
if(this->get_limit(channel_name) != -1 && (size_t)this->get_limit(channel_name) <= channels[channel_name]->getUsers().size())
{
    std::string msg = ":" + this->get_hostnames() + " 471 " + this->get_nickname(fd) + " " + channel_name + " :Cannot join channel (+l)\r\n";
    send(fd, msg.c_str(), msg.length(), 0);
    return (1);
}
if (it2 == channels.end())
{
    // Channel doesn't exist, create it
    Channel* newChannel = new Channel(channel_name); // Create a new channel
    newChannel->addUser(this->get_nickname(fd)); // Add the user to the channel
    newChannel->addOperator("@" + this->get_nickname(fd)); // Make the user an operator with '@' prefix
    newChannel->set_creater(true);
    if(!key.empty())
        newChannel->setChannelKey(key); // Set the channel key
    channels[channel_name] = newChannel; // Add the channel to the map
The checks JOIN runs, in order
JOIN runs its checks in a fixed order and answers with the standard numeric code as soon as one fails. If all pass, the first member becomes the operator and everyone in the channel sees the JOIN.Open full size

Relaying is then a loop over the channel's members: the server looks up each member's socket and sends them the line, with the sender's nick!user@host prefix so clients know who spoke.

src/privmsg.cppView on GitHub
void Server::send_to_channel(std::string channel_name , std::string str ,int fd)
{
    std::string message;
    std::map<std::string, Channel*>::iterator it = this->getChannels().begin();
    for (; it != this->getChannels().end(); it++)
    {
        if(it->first == channel_name)
        {
            std::set<std::string>::iterator it2 = it->second->getUsers().begin();
            for (; it2 != it->second->getUsers().end(); it2++)
            {
                int user = this->get_fd_users(*it2);
                if(user != fd)
                {
                    message = ":" + this->get_nickname(fd) + "!" + this->get_username(fd) + "@" + this->get_ip_address(user) + " PRIVMSG " + channel_name + " :" + str + "\r\n";
                    send(user, message.c_str(), message.length(), 0);
                }
            }
        }
    }
}
Channel modes and how a message is relayed
Operators control a channel with five modes; anyone else trying gets 482. Sending to a channel is one line in and many out, with a prefix saying who spoke.Open full size

Empty channels are deleted automatically when their last member leaves or disconnects, and PRIVMSG, JOIN, PART and KICK all accept several targets separated by commas.

The bonus bot

For the bonus, the bot is a separate program that connects to the server like any other client, with the nickname Bot. Users can ask it for the time, a list of commands, or the 42 level of a student (level <login>), read from a data file. The server forwards those questions to the bot, and the bot's answers come back with a special prefix so the server knows to deliver them to the person who asked.

Two small details keep the server alive in practice. Writing to a client that has just disconnected raises SIGPIPE, which would kill the process by default, so it is ignored. And Ctrl+C sets a flag that ends the loop cleanly instead of killing it mid-write:

src/main.cppView on GitHub
int main(int ac, char **av)
{
    if (!parsingInput(ac, av))
        return (1);
    signal(SIGINT, handl_signal);
    signal(SIGPIPE, SIG_IGN);
    std::cout << Welcome << std::endl;
    Server server;
    server.setPort(atoi(av[1]));
    server.setServerPassword(av[2]);
    std::cout<< "\t[\033[32;1mINFO\033[0m] \033[32;1mServer is running on port \033[0m[\033[32;1m" << server.getPort() << "\033[0m]\n" << std::endl;
    if (!server.initServer())
        return (0);
    server.runServer(close_ser);

Lessons and improvements

  • Network code is mostly about edge cases. Half-received lines, clients vanishing mid-command, nicknames changing while in channels: the happy path is the easy part.
  • Protocols are contracts. Real clients only behave if the numeric replies and message formats match what they expect. The server works with irssi, WeeChat, HexChat, LimeChat and plain nc.
  • What I would improve today. The loop calls poll() with a timeout of 0, so it spins even when nothing happens; a timeout of −1 would let the process sleep. Writes go straight to send(), which on a slow client can send only part of a message; a per-client output buffer flushed on POLLOUT would fix that. And when several complete lines arrive in one recv(), each should be run as its own command.

The full source, with a README covering every command, mode and numeric reply, is on GitHub.

About the project: ft_irc

An Internet Relay Chat server built from scratch in C++98 in a team of two. One process and a single poll() loop serve many clients at once, and real clients such as irssi, HexChat and WeeChat connect to it like any IRC network.

  • poll() event loop
  • Works with irssi
  • RFC 1459

Built with

  • C++98
  • Sockets
  • poll()
  • TCP/IP
  • RFC 1459
  • Make