gpt4 book ai didi

c - 套接字返回 'No such file or directory"

转载 作者:太空狗 更新时间:2023-10-29 14:53:44 27 4
gpt4 key购买 nike

Linux GCC 4.4.2

我正在做一些套接字编程。

但是,当我尝试从套接字函数分配 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");
}

用老式方法编辑 == 编码

    int32_t sockfd = 0;
struct sockaddr_in my_addr;

memset(&my_addr, 0, sizeof(my_addr));

my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(6000);
my_addr.sin_addr.s_addr = inet_addr("127.0.0.1");

sockfd = socket(PF_INET, SOCK_STREAM, 0);
if(sockfd == -1)
{
fprintf(stderr, "Socket failed [ %s ]\n", strerror(errno));
return;
}

if(bind(sockfd, (struct sockaddr *) &my_addr, sizeof(my_addr)) == -1)
{
fprintf(stderr, "Bind failed [ %s ]\n", strerror(errno));
return;
}

最佳答案

您的主要问题是您对 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)

关于c - 套接字返回 'No such file or directory",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1879217/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com