C 插座返回';没有这样的文件或目录;

C 插座返回';没有这样的文件或目录;,c,sockets,C,Sockets,Linux GCC 4.4.2 我正在做一些套接字编程 然而,当我尝试从socket函数分配sockfd时,我总是会遇到这个错误 " Socket operation on non-socket" 非常感谢你的建议 #if defined(linux) #include <pthread.h> /* Socket specific functions and constants */ #include <sys/types.h> #include <sys/soc

Linux GCC 4.4.2

我正在做一些套接字编程

然而,当我尝试从socket函数分配sockfd时,我总是会遇到这个错误

" Socket operation on non-socket"
非常感谢你的建议

#if defined(linux)
#include <pthread.h>
/* Socket specific functions and constants */
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <errno.h>
#endif

#include "server.h"
#include "cltsvr_ults.h"

/* Listens for a connection on the designated port */
void wait_client()
{
    struct addrinfo add_info, *add_res;
    int sockfd;

    /* Load up the address information using getaddrinfo to fill the struct addrinfo */
    memset(&add_info, 0, sizeof(add_info));
    /* Use either IPv4 or IPv6 */
    add_info.ai_family = AF_UNSPEC; 
    add_info.ai_socktype = SOCK_STREAM;
    /* Fill in my IP address */
    add_info.ai_flags = AI_PASSIVE;

    /* Fill the struct addrinfo */
    int32_t status = 0;
    if(status = getaddrinfo(NULL, "6000", &add_info, &add_res) != 0)
    {
        fprintf(stderr, "getaddrinfo [ %s ]\n", gai_strerror(status));

        return;
    }

    if((sockfd = (socket(add_res->ai_family, add_res->ai_socktype, add_res->ai_protocol)) == -1))
    {
        fprintf(stderr, "Socket failed [ %s ]\n", strerror(errno));

        return;
    }

    /* Bind to the port that has been assigned by getaddrinfo() */
    if(bind(sockfd, add_res->ai_addr, add_res->ai_addrlen) != 0)
    {
        fprintf(stderr, "Bind failed [ %s ]\n", strerror(errno));

        return;
    }

    printf("Listening for clients\n");
}

您的主要问题是,当socket()出现错误时,您的检查是错误的。socket()在出错时返回-1,而在成功时返回0。您可能会得到一个好的套接字值(2、3等),并将其视为一个错误

在插入代码的方式上还有第二个问题。当你写作时:

if (sockfd = socket(add_res->ai_family, add_res->ai_socktype, add_res->ai_protocol) != 0)
被视为:

if (sockfd = (socket(add_res->ai_family, add_res->ai_socktype, add_res->ai_protocol) != 0))
因此,sockfd将不会被分配socket的返回值,而是将其与0进行比较的值。要解决这两个问题,您应该写:

if ((sockfd = socket(add_res->ai_family, add_res->ai_socktype, add_res->ai_protocol)) == -1)

我认为您应该指定所需的套接字类型。当你说:

add_info.ai_family = AF_UNSPEC;
你应该说:

add_info.ai_family = AF_INET;

@robUK使用
getaddrinfo
而不是使用普通的
套接字(AF_INET,SOCK_STREAM,6000)有什么特别的原因吗?我使用的是getaddrinfo,因为这是最新的方法,而另一种方法已经过时了。我用的是比吉的参考资料。Thank.RageZ:
6000
不是socket.Thank的第三个参数的适当值。这是正确的。然而,我现在得到一个错误“非套接字上的套接字操作”。我已经用正确的行编辑了我的代码。我为什么会犯这个错误?许多的thanks@roboUK-您确定您从发布为“编辑”的代码中得到该错误吗。当我编译并运行该代码段时,它运行得很好。我将该行代码更改为AF_INET,但仍然得到相同的错误。我也不相信您对getaddrinfo()的调用是正确的。你为什么不简单地遵循一个关于如何使用套接字的“老派”示例呢。效果不错。但是,我仍然想知道为什么使用getaddrinfo()失败?非常感谢,,
add_info.ai_family = AF_INET;