Search code examples
csocketsmemset

C - Socket Networking - string's won't produce equality


I have been doing socket networking in C, for an application that will take a password from the client side for verification at the server. I've set everything up and the sockets communicate but when I send a string over and use strcmp() the strings, despite being the same when printed out, won't return 0 (which I believe indicates the strings are the same) like so:

Note the client and server side are separate programs, going through localhost on my machine.

/*Client Side */

char password[64] = {0};

fgets(password, 64, stdin);

write(sockfd, password, 64);



/*Server Side */

char password[64] = "password";

char password_buffer[64];

read(newsockfd, password_buffer, 64);

if(strcmp(password, password_buffer) != 0)
    {
    printf("Password Incorrect\n");
    {
else 
    {
    printf("Password correct\n");
    }

Any help would be greatly appreciated. It has occured to me that the use of bzero or memset may be involved, although I'm not sure how these are implicated.


Solution

  • fgets(password, 64, stdin); likely adds a trailing new-line character (\n) at end of string. Remove it from the client string after fgets, or add one at end of compare string on the server side.

    To remove the trailing new-line from the client string, use e.g. this:
    password[strcspn(password, "\r\n")] = 0;