为什么 put 函数不能处理 C++ 中套接字的输入字符?
这是我的运行登录管理器的服务器的代码,该代码将恶意访问登录到文件中并打印出错误登录的结果。 字符 user 和 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;
}
好吧,问题在于输出控制台和日志文件中的输出。
就像这样:
Login error with user: lol
password: asd
:��ܔ��P{w� from: 127.0.0.1
为什么会有奇怪的 asci 字符? 由于新行来自套接字的用户输入,如何避免新行?
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.
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?
How can avoid the new line since they come from user input by socket?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如很多人评论的那样,这段代码不包含任何特定于 C++ 的内容,因此我的回答就好像您正在使用纯 C 语言一样。
我猜测,由于您在上面使用了
memcmp
,因此您的输入字符串不是以空字符结尾的。strcat
将继续从指针所到之处追加char
,直到遇到'\0'
。如果您想将用户或密码用作 C 样式字符串,则需要添加空终止符,否则使用strncat
并传递长度。另外,请注意
msg
溢出。使用snprintf
来格式化消息可能会更好,因为它接受最大输出字符串长度。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.
I'm guessing, since you use
memcmp
above, that your input strings are not null terminated.strcat
will keep on appendingchar
s from whatever the pointer wanders into until it runs into a'\0'
. You'll need to add a null terminator if you want to use user or password as a C-style string, or else usestrncat
and pass the length.Also, beware of overrunning
msg
. You might have better luck usingsnprintf
to format your message, since it accepts a maximum output string length.这样你可以让你的代码变得更小一点,
在 if 语句之前添加这个额外的代码,你可以确保字符串有效
This way you could make your code little bit smaller
adding this extra code before if-statement you could ensure strings are valid