AND 运算符在 C 中未按预期工作

AND operator not working as expected in C

你好我有一个简单的认证客户端来获取用户名和密码,要么显示继续要么拒绝,服务器用户名和密码设置为admin并通过。但是,当我 运行 它时,只要管理员或用户名之一与服务器的用户名密码匹配,它就会显示继续。无法弄清楚哪里出了问题,我使用 strcmp 比较 if 语句中的字符串的方式是否错误?

这是我的代码 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,它存储在 sendbuffer 中并通过 send(sock,.....)

发送到 authServer.c 的方式
        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");

我假设你想要的逻辑更像这样:

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

所以测试用户和密码是否都等于您比较的值。

将字符串与 strcmp() 进行比较:

This function starts comparing the first character of each string. If they are equal to each other, it continues with the following pairs until the characters differ or until a terminating null-character is reached.

Returns:

  • <0 第一个不匹配的字符在 ptr1 中的值低于 ptr2
  • 0 两个字符串的内容相等
  • >0 第一个不匹配的字符在 ptr1 中的值大于 ptr2

因此,为了查看字符串是否匹配,您需要检查 return 值是否为 0:
if(strcmp(usernameServer, username) == 0 && strcmp(passwordServer, password) == 0)

cpp reference - strcmp