开发者

if/else control flow problems

开发者 https://www.devze.com 2023-02-13 16:29 出处:网络
if (strcmp(buffer,\"change work\")==0) { close(newsockfd);/*closing the old port*/ close(sockfd); printf(\"Changing port to 51717....\\n\");
if (strcmp(buffer,"change work")==0)
{
   close(newsockfd);                   /*closing the old port*/
   close(sockfd);
   printf("Changing port to 51717....\n");
   sockfd = socket(AF_INET, SOCK_STREAM, 0);
   if (sockfd < 0)
   error("ERROR opening socket");
   bzero((char *) &serv_addr, sizeof(serv_addr));
   portno = atoi("51717");
   serv_addr.sin_family = AF_INET;
   serv_addr.sin_addr.s_addr = INADDR_ANY;
   serv_addr.sin_port = htons(portno);
   if (bind(sockfd, (struct sockaddr *) &serv_addr,  sizeof(serv_addr)) < 0)     /*binding with the new port*/
   error("ERROR on binding");
   listen(sockfd,5);
   clilen = sizeof(cli_addr);
   newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
   if (newsockfd < 0)
   error("ERROR on accept");
   printf("port changed\n");
   bzero(buffer,256);
   n = read(newsockfd,buffer,255);
   if (n < 0) error("ERROR reading from socket");
   printf("Here is the message: %s\n",buffer);
   n = write(newsockfd,"I got your message",18);
   if (n < 0) error("ERROR writing to socket");
  }
  else
  {
   printf("Here is the message: %s\n",buffer);
   n = write(newsockfd,"I got your message",18);
   if (n < 0) error("ERROR writing to socket");
   close(newsockfd);
   close(sockfd);
  }

In the above code when the condition is satisfied, bot开发者_运维百科h the codes are being executed instead of code1. This loop is not working properly. what may be the reason??? I want to focus on if part.


Two approaches to solving this:

a). Step in a debugger, you're quite likely to see that your code isn't quite as you think.

b). replace your complex code with a simple construct.

if (strcmp(buffer,"change work")!=0) 
   { printf("yes") } 
else 
   {  printf("no"); }

You will see that this works just fine, then make incremental changes to turn it back into your real code, at some point you'll go "aha".

Edited in light of your last comment:

My guess is that buffer does not contain exactly "change work" but perhaps also a newline character or other such delimiter. You would probably be benefit from adding diagnostic trace statements to show the buffer contents, use java.util.logging or log4j.

0

精彩评论

暂无评论...
验证码 换一张
取 消