gpt4 book ai didi

c - Operation now in progress on connect(function) 错误

转载 作者:太空狗 更新时间:2023-10-29 16:33:31 24 4
gpt4 key购买 nike

我想设置函数连接的超时值,但出现此错误:“操作正在进行中”

我的代码:

if ((he = gethostbyname(authdefhost)) == NULL) {
snprintf(errbuf, CERRBUFSIZ - 1, "cannot resolve %s: %s\n", authdefhost, hstrerror(h_errno));
return -1;
}

sin.sin_family = AF_INET;
memcpy(&sin.sin_addr, he->h_addr_list[0], sizeof(struct in_addr));

if ((sd = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
snprintf(errbuf, CERRBUFSIZ - 1, "cannot create client socket: %s\n", strerror(errno));
return -1;
}

if ((fcntl(sd, F_SETFL, O_NONBLOCK) < 0))
printf("error on setting socket flags.");

if (connect(sd, (void *) & sin, sizeof(sin)) == -1) {
snprintf(errbuf, CERRBUFSIZ - 1, "cannot connect to server %s: %s\n", authdefhost, strerror(errno));
close(sd);
return -1;
}

FD_ZERO(&fdset);
FD_SET(sd, &fdset);
int rv;
if ((rv = select(sd + 1, NULL, &fdset, NULL, &tv)) == -1) {
printf("error occurred on select function.");
return -1;
}
else if (rv == 0) {
printf("time out occurred.");
return -1;
}
else {
printf("connection established");
return sd;
}

最佳答案

当您在非阻塞套接字上调用 connect() 时,您将得到 EINPROGRESS 而不是阻塞等待连接握手完成。然后,您必须通过 select() 进行可写性检查,并检查套接字错误以查看连接是否已完成。

来自 Linux 的 connect() manpage :

EINPROGRESS    The socket is nonblocking and the connection cannot be completed    immediately.  It is possible to select(2) or poll(2) for completion by    selecting the socket for writing.  After select(2) indicates    writability, use getsockopt(2) to read the SO_ERROR option at level    SOL_SOCKET to determine whether connect() completed successfully    (SO_ERROR is zero) or unsuccessfully (SO_ERROR is one of the usual    error codes listed here, explaining the reason for the failure).

关于c - Operation now in progress on connect(function) 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6202454/

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