【问题标题】:accept fails with EFAULT接受失败并显示 EFAULT
【发布时间】:2011-03-09 20:05:50
【问题描述】:

我有一个在多台机器上运行的套接字服务器。除了在一台机器上之外,它就像一个魅力。

服务器绑定正确,但在客户端尝试连接时返回错误(EFAULT)。

也许有人知道问题的根源是什么。提前非常感谢!

关于机器的一些信息: Linux 版本 2.6.18.3 gcc 版本 3.3.5 (Debian 1:3.3.5-13)

套接字服务器源非常简单。

...
...
struct sockaddr_in server_addr;
struct sockaddr* client;
socklen_t alen;


sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1) {
    ...
}

server_addr.sin_family = AF_INET;
server_addr.sin_addr.s_addr = INADDR_ANY;
server_addr.sin_port = htons(port);

if(bind(sockfd, (struct sockaddr *) &server_addr, sizeof(server_addr)) < 0){
    ...
}

if(listen(sockfd,BACKLOG) == -1){
    ...
}

alen = sizeof(client);

new_fd = accept(sockfd, client, &alen);
if (new_fd == -1) {
        /*
        * this part of the code is executed
        * errno is set to 14
        */
}

感谢您为我指明了正确的方向。

【问题讨论】:

    标签: c linux sockets tcp


    【解决方案1】:

    使用这个:

    struct sockaddr_in client;
    ...
    alen = sizeof(client);
    new_fd = accept(sockfd, (struct sockaddr *) &client, &alen);
    

    accept 需要一个指向现有缓冲区的指针,它将被填充。您有两个错误,您将 alen 设置为 指针 的大小,并传递一个未初始化的指针以接受.

    【讨论】:

    • 非常感谢 Eric 的快速帮助!你的建议解决了这个问题。祝你有美好的一天!
    【解决方案2】:

    来自accept(2) 手册页:

      EFAULT The addr argument is not in a writable part of the user  address
              space.
    

    检查以确保您已正确分配client。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-01-03
      • 2014-07-21
      • 2012-07-10
      • 2014-11-18
      • 2015-12-31
      • 1970-01-01
      • 2021-12-10
      • 2020-02-08
      相关资源
      最近更新 更多