Search code examples
coperator-keywordstrcmp

AND operator not working as expected in C


Hi I have a simple authentication client to get username and password, either display proceed or denied, the server username and password is set to admin and pass. However when I run it, as long as one of the admin or username matches the servers' username password, it displays proceed. Can't figure out what is wrong, is the way i compare the strings in my if statement wrong using strcmp?

Here is my code authServer.c

char recvbuffer[BUFSIZE], sendbuffer[BUFSIZE], username[20], password[20], 
    usernameServer[20] = {"admin"}, passwordServer[20] = {"pass"};

sscanf(recvbuffer, "%s %s", username, password);
    
    if((strcmp(usernameServer, username) && strcmp(passwordServer, password)) == 0)
    {
        snprintf(sendbuffer, sizeof(sendbuffer), "%s", PROCEED);    
    }
    else
    {
        snprintf(sendbuffer, sizeof(sendbuffer), "%s", DENIED);
    }

    ssize_t numBytesSent = send(clntSock, sendbuffer, strlen(sendbuffer), 0);

authClient, the way how it's store in sendbuffer and sent to authServer.c by send(sock,.....)

        printf("\nEnter username (10 characters max):\n");
        fgets(username, sizeof(username), stdin);
        strcat(sendbuffer, username);
        strcat(sendbuffer, " ");

        printf("\nEnter password (10 characters max):\n");
        fgets(password, sizeof(password), stdin);
        strcat(sendbuffer, password);
        strcat(sendbuffer, "\r\n\r\n");

Solution

  • I assume the logic you want is more like this:

    if((strcmp(usernameServer, username) == 0) && (strcmp(passwordServer, password) == 0))
    

    So testing if user AND password are both equal to the value you compare them to.