C程序挂在strcmp附近

时间:2015-04-14 18:41:27

标签: c sockets strcmp

我正在client-server socket中构建C模拟我从客户端接受TCP connection,然后客户端向我的服务器发送消息。我成功收到了该消息,然后我遍历array structs struct Mapping { char key[6]; char value[8]; } MapElement; int main { char buf[BUFSIZE]; /* BUFSIZE 2048 */ int size = 4; struct Mapping serverMap[size]; initialize_server_map(serverMap); /* This method works, so not displaying in SO */ /* ... socket stuff (this works as seen from print statements) */ recvlen = recv(rqst, buf, BUFSIZE, 0); printf("The received length is %d\n", recvlen); printf("The buf is: %s\n", buf); if (recvlen > 0) { buf[recvlen] = 0; printf("The Server 2 has received a request with key %s\n", buf); char* buf_for_token[10]; strcpy(buf_for_token, buf); const char s[2] = " "; char *token; token = strtok(buf_for_token, s); token = strtok(NULL, s); int found = 0; for(int i = 0; i < sizeof(serverMap) / sizeof(struct Mapping); i++) { printf("Token: %sServerMapEntry: %s\n", token, serverMap[i].key); printf("Compare: %d\n", strcmp(serverMap[i].key, token)); if (strcmp(serverMap[i].key, token) == 0) { printf("What is wrong?!?! Why is this not printing?!\n"); found = 1; strcpy(post, "POST "); strcat(post, serverMap[i].value); if (send(rqst, post, strlen(post), 0) < 0) { perror("sendto"); } break; } } } } 寻找字符串匹配

The received length is 9
The buf is: GET key05
The Server 2 has received a request with key GET key05
Token: key05ServerMapEntry: key05
Compare: 0

我的输出是:

{{1}}

我无法理解为什么下一个打印声明没有打印。我的节目永远都是悬而未决的。 :(

2 个答案:

答案 0 :(得分:6)

这里有一个错误:

char* buf_for_token[10];
strcpy(buf_for_token, buf);

你怎么设法编译这个程序? buf_for_token是指向char的指针数组,它应该只是char的数组,并且足够大:

char buf_for_token[BUFSIZE];
strcpy(buf_for_token, buf);

此缓冲区应该与接收缓冲区一样大,并且如评论中所述,您应该将1小于其大小的recv传递给'\0',以便为{{保留一个额外的字节1}}你最后强迫:

recvlen = recv(rqst, buf, sizeof(buf) - 1, 0);

for循环中,使用size代替sizeof(serverMap) / sizeof(struct Mapping)sizeof(serverMap) / sizeof(*serverMap)

至于为什么printf("What is wrong?!?! Why is this not printing?!\n");没有输出任何内容,请在fflush(stdout);之后尝试printf(),以确保它不仅仅是缓冲问题。

或者也可能是您没有发布确切的代码... post未定义,并且函数原型缺少一些正文部分:

int main
{

最后,如果您的套接字是TCP,请注意,客户端发送的数据可能会被服务器以不同大小的块接收,大小越小。唯一的保证是字节流的顺序。你不应该依赖大多数时候你收到一整行的事实。网络拥塞或除了yoyr控制之外的其他条件可能导致数据包被切片并以小块接收或组合在包含多行的较大块中...为了处理服务器中的这种潜在情况,您应该缓冲数据并一次处理一行

答案 1 :(得分:2)

这一行:
char* buf_for_token[10];
说:创建一个包含char的10个元素指针数组 我相信你需要那个:
char buf_for_token[10];