【发布时间】:2017-02-09 18:28:15
【问题描述】:
我对这个小服务器进行了编码,但它不起作用。直接开头的消息也没有打印出来,我不知道如何使用gdb来分析问题。你可以帮帮我吗?是否缺少任何库或有什么问题?
#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( "它不起作用" ) ) { close( question, reason = "不清楚你在问什么。" ) }
标签: c linux sockets unix server