我編寫了這個小服務器,它不起作用。直接在開頭的消息也沒有打印出來,我不知道如何使用gdb分析問題。你可以幫幫我嗎?有沒有圖書館丟失或最新錯誤?c中的簡單服務器不起作用
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 7890
int main(void) {
printf("HelloWorld");
int sockfd, sock_client;
if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
printf("Could no open socket\n");
}
int yes = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof (int)) == -1) {
printf("Coud not reuse\n");
}
printf("socket was created");
struct sockaddr_in sockaddr_host, sockaddr_client;
sockaddr_host.sin_family = AF_INET;
sockaddr_host.sin_port = htons(PORT);
sockaddr_host.sin_addr.s_addr = 0;
memset(&(sockaddr_host.sin_zero), '\0', 8);
if (bind(sockfd, (struct sockaddr *) &sockaddr_host, sizeof (sockaddr_host)) == -1) {
printf("Could not bind socket");
}
if (listen(sockfd, 1) == -1) {
printf("Could not start listening");
} else {
printf("Server is listening on %s: %d", inet_ntoa(sockaddr_host.sin_addr), ntohs(sockaddr_host.sin_port));
}
while (1) {
socklen_t client_length = sizeof (sockaddr_client);
if ((sock_client = accept(sockfd, (struct sockaddr *) &sockaddr_client, &client_length)) == -1) {
printf("Could not accept connection");
}
printf("sever: got connection from %s on port %d", inet_ntoa(sockaddr_client.sin_addr), ntohs(sockaddr_client.sin_port));
char message[] = "Hello\n";
if (send(sockfd, message, sizeof (message), 0) == -1) {
printf("Could not send message");
}
close(sock_client);
close(sockfd);
}
return 0;
}
你的意思是「HelloWorld」不打印?請更具體地解釋,你的輸出是什麼,以及你的期望。 –
if(question.contains(「It does not work」)){close(question,reason =「Unclear what you ask。」)} –