-1

I have two programs in C:
a client and a server.

I'm not going to develop all the details of the code, things work fine. Except for this point: I want my server to send colored acknowledgment messages and my client to identify them.

On the server the lines look like this:

    //server side there there is:
    FILE * stream; // for the socket

    fprintf(stream,"\x1b[31m220\x1B[0m GET command received please type the file name\n");
    //here stream refers to a classic BSD socket which connect client to server
    //\x1b[31m colors text in red
    //\x1B[0m put back text color to normal

And I wonder what code should I use to detect the acknowledgment on the client:

    //Client side there is:
    FILE * stream; // for the socket (client side)
    char buffer[100]; //to receive the server acknowledgment

    //fgets put the received stream text in the buffer:
    fgets (buffer , sizeof buffer, stream);
    
    //Here strncmp compares the buffer first 11 characters with the string "\x1b[31m220"
    if (strncmp (buffer, "\x1b[31m220",11)== 0)
    {
    printf("\x1B[48;5;%dmCommand received\x1B[0m%s\n",8,buffer);
    }

Things don't work. I wonder what should I put instead of "\x1b[31m220",11 in the client to make things work. I suspect some characters of the color code to be interpreted and therefor to disappear from the string, but which ones?


There is an explanation of the color code here: stdlib and colored output in C

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
  • `//Here strncmp compares the buffer first 11 characters` that's the problem, `\x1b` occupies only 1 character, it is an escape code, it should be 8. – David Ranieri Jun 28 '20 at 08:32

2 Answers2

1

"\x1b[31m220" has 8 characters, not 11. strncmp is going to fail at 9th character which is '\0' in this string and '\x1B' in the buffer.

1

Make your life easier and let compiler calculate the sizes for you:

#define COLOURCODE "\x1b[31m220"

if (strncmp (buffer, COLOURCODE, sizeof(COLOURCODE) - 1)== 0)
0___________
  • 60,014
  • 4
  • 34
  • 74