【问题标题】:Simple server in c does not workc中的简单服务器不起作用
【发布时间】: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


【解决方案1】:

如果你缺少一个库,链接器就会抱怨。

标准输出通常是行缓冲的。在HelloWorld 之后添加一个换行符,您至少会看到第一个输出。

printf("HelloWorld\n");

与其他printf相同。


\n添加到每个printf后,你会看到

你好世界
套接字已创建
服务器正在监听 0.0.0.0: 7890

当您现在连接到您的服务器时,例如netcat

nc localhost 7890

你的服务器会输出

服务器:从端口 36496 上的 127.0.0.1 获得连接


但仍有一些错误。

if(send(sockfd, message, sizeof(message), 0) == -1) {

应该是

if(send(sock_client, message, sizeof(message) - 1, 0) == -1) {

否则服务器将消息发送给它自己。 sizeof(message) 还包括最后的 \0

最后,你不应该close(sockfd);,如果你想在第一个之后继续接收更多的连接请求。

【讨论】:

  • 这应该是评论吧?
  • 耐心你必须有我的年轻学徒,SCNR ;-)
  • 红灯摄像头说“游戏你是系统”
  • 触摸! ... :-)
【解决方案2】:

如你所说

开头的消息也没有打印出来

printf 之后添加fflush

printf("HelloWorld");
fflush(stdout);

是否缺少任何库

我不认为缺少任何库,因为您已成功编译程序并创建了可执行文件。

【讨论】:

    猜你喜欢
    • 2015-10-24
    • 2016-10-19
    • 2015-05-26
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 2017-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多