Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8826439
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T07:08:19+00:00 2026-06-14T07:08:19+00:00

I’m studying Linux/UNIX sockets, so I wrote a very simple game based on it,

  • 0

I’m studying Linux/UNIX sockets, so I wrote a very simple “game” based on it, called “21 matches”. There’s a heap that consists of 21 matches, and each player takes one, two or three matches from it. The person who takes the last match loses the game.

Obviously, the key to winning is to complement your opponent’s turn up to 4 matches, so he has to take the very last match (works only if you do the first turn). So, client connects to the server and “plays” against the server till he loses. There can be more than one client connected, so I limit the number of connection, making my host reject any further ones.

The only thing I can’t fix or explain is that when someone’s getting rejected, the very first client loses the game immediately, even if he hasn’t made any turns. This might be explained if I let the new client touch any client’s heap, but I don’t! I also tracked the buffer array, but it doesn’t get harmed in any way.

Here’s the code:

#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <stdio.h>
#include <poll.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

void die (const char *s, int errcode);
int mkservsock();
void acceptclient();
void dropclient (int client);
void make_turn (int client);

enum
{
  port   = 3333,
  buf_s  = 100,
  limit  = 3
};

void die (const char *s, int errcode)
{
  perror (s);
  exit (errcode);
}

struct pollfd fds[limit + 1];  // client socket descriptors array
int left[limit + 1];           // how many matches left
int nfd = 1;                   // number of the next client
char buffer[buf_s];            // buffer for communicating

// creates a single socket to poll
int mkservsock()
{
  int s = socket (AF_INET, SOCK_STREAM, 0);
  struct sockaddr_in addr;
  addr.sin_family = AF_INET;
  addr.sin_port = htons (port);
  addr.sin_addr.s_addr = INADDR_ANY;
  if (bind (s, (struct sockaddr *)&addr, sizeof(addr)) == -1)
    die ("Can't bind socket", 1);

  if (listen (s, 1) == -1)
    die ("Can't start listening", 1);

  return s;
}

// adds new client to descriptors array or rejects it, if number of connections exceeds the limit
void acceptclient()
{
  int c = accept (fds[0].fd, 0, 0);
  fds[nfd].fd = c;
  fds[nfd].events = POLLIN;
  if (nfd == limit + 1)
  {
    sprintf (buffer, "Server is busy, try again later\n");
    send (fds[nfd].fd, buffer, strlen (buffer), 0);
    close (fds[nfd].fd);
    return;
  } else
  {
    left[nfd] = 21;
    sprintf (buffer, "Matches available: %d\nTake 1, 2 or 3!\n", left[nfd]);
    send (fds[nfd].fd, buffer, strlen (buffer), 0);
    nfd++;
  }
}

// disconnects a client in case of match ending or inappropriate data sent
void dropclient (int client)
{
  int i, j;
  close (fds[client].fd);
  for (i = client; i < nfd - 1; i++)
  {
    fds[i] = fds[i + 1];
    left[i] = left[i + 1];
  }
  nfd--;
}


void make_turn (int client)
{
  int n = recv (fds[client].fd, buffer, buf_s, 0);
  if (n == 0) {
    dropclient (client);
    return;

  } else if (n > 3)
  {
    // input counts as incorrect if it contains more than 1 symbol,
    // since we expect a single digit and nothing else
    // (yep, we get two extra bytes when receiving a message)
    sprintf (buffer, "I can break rules, too. Goodbye.\n");
    send (fds[client].fd, buffer, strlen (buffer), 0);
    dropclient (client);
    return;
  }

  // way to extract a digit from the character
  int received = buffer[0] - '0';  
  if (received > 3 || received <= 0)
  {
    sprintf (buffer, "You're allowed to take 1, 2 or 3 matches only\n");
    send (fds[client].fd, buffer, strlen (buffer), 0);
    return;

  } else if (received > left[client])
  {
    sprintf (buffer, "You can't take more than %d\n", left[client]);
    send (fds[client].fd, buffer, strlen (buffer), 0);
    return;

  } else  
  {
    // obviously, it happens only when there's the only match,
    // and the client has to take it
    if (left[client] == received)
    {
      sprintf (buffer, "You lost!\n");
      send (fds[client].fd, buffer, strlen (buffer), 0);
      dropclient (client);
      return;

    } else
    {
      // sort of "keeping the game up"
      left[client] -= 4;
      sprintf (buffer, "Matches left: %d (I took %d)\n", left[client], 4 - received);
      send (fds[client].fd, buffer, strlen (buffer), 0);
      return;
    }  
  }
}

int main (int argc, char *argv[])
{
  fds[0].fd = mkservsock ();
  fds[0].events = POLLIN;

  for (;;)
  {
    int status, i;
    status = poll (fds, nfd, -1);
    if (status == -1)
      die ("Error while polling", 1);

    if (fds[0].revents & POLLIN)
      acceptclient();

    for (i = 1; i < nfd; i++)
    {
      if (fds[i].revents & POLLERR)
      {
        printf ("Got troubles on %d\n", i);
        continue;
      }

      if (fds[i].revents & POLLIN)
        make_turn (i);
    }
  }
}

And here’s the thing happening to the first client after reaching max. number of connections:

Matches available: 21
Take 1, 2 or 3!

(don’t take anything, meanwhile someone connects and gets rejected)

(after this, post any number and it’ll say that there’s only one match in the heap)

1
You lost!

Note that you lose if and only if your input is equal to a number of matches left. So, what’s going on?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T07:08:21+00:00Added an answer on June 14, 2026 at 7:08 am

    You overwrite left[], when you call acceptclient() and don’t check if there’s room in fds to store the new connection.

    You first initialize the new client fds and afterwards reject the connection, but then it is too late, because you have written one entry beyond the array. And beyond the array, there’s the left[] array, which now has a 1 or 0 stored in it. So, no matter how the first client responds, he always takes the last.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a small JavaScript validation script that validates inputs based on Regex. I
I am doing a simple coin flipping experiment for class that involves flipping a
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I know there's a lot of other questions out there that deal with this
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
link Im having trouble converting the html entites into html characters, (&# 8217;) i
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
Configuring TinyMCE to allow for tags, based on a customer requirement. My config is
I've got a string that has curly quotes in it. I'd like to replace

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.