我在比较 C 中的字符串时遇到了麻烦(我对它很陌生)。我在此服务器应用程序上有套接字,等待接受来自客户端的数据。在我程序的这个特定部分中,我希望能够根据从客户端接收到的数据执行 MySQL 查询。我希望能够知道接收到的数据何时具有“newuser”的值来启动一个简单的注册过程。strcmp 返回一个正值 1 ,我相信我应该得到一个 0 因为值应该相等。
源代码:
//setup socket
//loop and select structure to handle multiple connections
if ((nbytes = recv(i, buf, sizeof buf, 0)) <= 0) {
// got error or connection closed by client
if (nbytes == 0) {
// connection closed
printf("selectserver: socket %d hung up\n", i);
} else {
perror("recv");
}
close(i); // bye!
FD_CLR(i, &master); // remove from master set
} else {
char check[] = "newuser";
char fromUser[sizeof check];
strncpy(fromUser,buf, sizeof check);
printf("length of fromUser: %d\n", sizeof fromUser);
printf("length of check: %d\n", sizeof check);
printf("message from user: %s\n", fromUser);
printf("check = %s \n", check);
int diff = strcmp(fromUser, check);
printf("compare fromUser to check: %d\n", diff);
if ( strcmp(fromUser, check) == 0) {
printf("aha! new user");
}
输出:
length of fromUser: 8
length of check: 8
newuser from user: newuser
check = newuser
compare fromUser to check:
我有一种感觉,我没有正确处理传入缓冲区或错误地复制缓冲区。