连接(函数)错误上的操作正在进行错误 [英] Operation now in progress error on connect( function) error

查看:14
本文介绍了连接(函数)错误上的操作正在进行错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置函数connect的超时值,但我得到这个错误:Operation now in progress"

I want to set timeout value of function connect but I get this error: "Operation now in progress"

我的代码:

if ((he = gethostbyname(authdefhost)) == NULL) {
        snprintf(errbuf, CERRBUFSIZ - 1, "cannot resolve %s: %s
", 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
", 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
", 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() 进行可写性,并检查套接字错误以查看连接是否已完成.

When you call connect() on a non-blocking socket, you'll get EINPROGRESS instead of blocking waiting for the connection handshake to complete. Then, you have to select() for writability, and check the socket error to see if the connection has completed.

来自 Linux 的 connect() 手册页:

From Linux's 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).

这篇关于连接(函数)错误上的操作正在进行错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆