简体   繁体   English

比较从 C 中的套接字接收的字符串数据

[英]Comparing string data received from a socket in C

I have a question on sockets.我有一个关于 sockets 的问题。 I have this code:我有这个代码:

while(bytes = recv(sClient, cClientMessage, 599, 0)){

This puts the message it recives into cClientMessage and the message is always "Message".这会将它接收到的消息放入 cClientMessage 中,并且消息始终是“消息”。 How I made an if statement like if(cClientMessage == "Message"){//do func} .我是如何做出if(cClientMessage == "Message"){//do func}这样的 if 语句的。 Now this code will not do the function I want.现在这段代码不会做我想要的 function 。 I think this is because it's not receiving the message right.我认为这是因为它没有正确接收消息。 Can someone help me?有人能帮我吗?

Try:尝试:

if( strcmp( cClientMessage, "Message")) == 0 ) {
   // do something
}

Edit, following suggestion from strager:编辑,遵循strager的建议:

A better solution, which does not depend on the received data being null terminated is to use memcmp:一个更好的解决方案是使用 memcmp,它不依赖于接收到的数据被 null 终止:

if( memcmp( cClientMessage, "Message", strlen( "Message") )) == 0 ) {
   // do something
}

First there is a bug in the code you wrote:首先,您编写的代码中有一个错误:

while(bytes = recv(sClient, cClientMessage, 599, 0)){

This is wrong because recv will return non zero if there is a socket error and your code will lead to an infinite loop.这是错误的,因为如果存在套接字错误,recv 将返回非零,并且您的代码将导致无限循环。 In particular you want to check for > 0特别是您要检查 > 0

char cClientMessage[599];
while((bytes = recv(sClient, cClientMessage, sizeof(cClientMessage), 0)) > 0)
{
  if(strlen("Message") == bytes && !strncmp("Message", cClientMessage, bytes))
  {
    //cClientMesssage contains "Message"
  }
} 

if(bytes == 0)
{
  //socket was gracefully closed
}
else if(bytes < 0)
{
  //socket error occurred
}

The problem with what you did: cClientMessage == "Message" is that if you compare a char* to a string literal, or a char[] to a string literal, then you will be comparing the pointer addresses and not the actual content.您所做的问题: cClientMessage == "Message" 是,如果您将 char* 与字符串文字进行比较,或者将 char[] 与字符串文字进行比较,那么您将比较指针地址而不是实际内容。

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

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