简体   繁体   English

为什么puts函数不能与C ++中套接字的输入字符一起使用?

[英]Why puts function doesn't work with input char from socket in C++?

This is my code for a server running a login manager, that log into a file the malicious access and print out the result of the wrong login. 这是我的用于运行登录管理器的服务器的代码,该服务器将恶意访问登录到文件并打印出错误登录的结果。 The chars user and pass come from the user input using the socket. chars用户和pass来自使用套接字的用户输入。

if ((memcmp(user, "admin", strlen("admin")) == 0)) {
    /*code... */
}
else {
    char msg[600];
    strcpy (msg,"Login error with ");
    strcat (msg,"user: ");
    strcat (msg,user);
    strcat (msg," password: ");
    strcat (msg,pass);
    strcat (msg," from: ");
    strcat (msg, client_ip);
    puts (msg);
    logfile->Write(msg);
    return false;
}

Well, the problem is the output both on the output console and in the logfile. 好吧,问题出在输出控制台和日志文件中。

Like this: 像这样:

Login error with user: lol

 password: asd

:��ܔ��P{w� from: 127.0.0.1

Why are there the strange asci chars? 为什么会有奇怪的asci字符? How can avoid the new line since they come from user input by socket? 由于新行来自套接字的用户输入,因此如何避免?

As multiple people have commented about, this snippet of code contains nothing C++ specific, so I'm answering as if you are working in plain C. 正如许多人所评论的那样,此代码段不包含特定于C ++的内容,因此我的回答就像是在纯C语言中一样。

I'm guessing, since you use memcmp above, that your input strings are not null terminated. 我猜,由于您在上面使用了memcmp ,因此您输入的字符串不是以null结尾的。 strcat will keep on appending char s from whatever the pointer wanders into until it runs into a '\\0' . strcat将继续将指针所不希望的内容附加到char ,直到遇到'\\0'为止。 You'll need to add a null terminator if you want to use user or password as a C-style string, or else use strncat and pass the length. 如果要使用用户或密码作为C风格的字符串,则需要添加一个空终止符,否则,请使用strncat并传递长度。

Also, beware of overrunning msg . 另外,要注意msg You might have better luck using snprintf to format your message, since it accepts a maximum output string length. 使用snprintf格式化消息可能会更好,因为它接受最大输出字符串长度。

This way you could make your code little bit smaller 这样,您可以使代码更小

if (strcmp(user, "admin") == 0) {
    /* yahoo, admin! */
}
else {
    char buff[256];
    snprintf(buff, sizeof(buff),
            "Login error with user: %s password: %s from: %s",
            user,
            pass,
            client_ip);
    printf("%s\n", buff);
    logfile->Write(buff);
    return false;
}

adding this extra code before if-statement you could ensure strings are valid 在if语句之前添加此额外代码,可以确保字符串有效

printf("user, len:%d, value: %s\n", strlen(user), user);
printf("pass, len:%d, value: %s\n", strlen(pass), pass);
printf("client_ip, len:%d, value: %s\n", strlen(client_ip), client_ip);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM