c - 套接字连接结束,操作正在非阻塞套接字上进行

标签 c linux sockets tcp

我在使用 connect() API 连接到目标 IP 时遇到问题。 connect() API 返回 -1 和 errno 作为操作正在进行

。我是否在建立连接之前过早检查返回码?请参阅以下代码片段:

struct sockaddr_in      servAddr;
        servAddr.sin_family = AF_INET;
            servAddr.sin_port = htons(9190); 
        const char * remoteIp = 10.10.20.86;
            rc = inet_pton(AF_INET,remoteIp, &servAddr.sin_addr);
            if (rc == -1 || errno == EAFNOSUPPORT)
            {
                return 0;
            }
            rc = connect(fd, (sockaddr*)&servAddr, sizeof(servAddr));
         if ( rc < 0) // this is where it fails. rc is -1.
                   {
                        log("connect failure with [%s]",strerror(errno));
                        print_sock_connect_error();
                   }

我有两个问题:

  1. 目标 IP 和端口 10.10.20.86:9190 正在等待连接,一旦收到连接,它就会将 ack 发送回源。我看到在 pcap 中建立了 tcp - ACK、SYN/ACK 和 ACK 到目的地,但仍然无法弄清楚为什么它返回 -1 并出现错误。那么我是否在连接建立完成之前检查rc? sysctl net.ipv4.tcp_syn_retries 设置为 6。
  2. 上面的代码有什么问题吗?

最佳答案

Am I checking the rc before the connection establishment is complete?

是的,你是。连接建立过程中的 TCP 乒乓操作并不是所有要做的事情。

Is there anything wrong with the code above?

嗯,是的,无论是处理 EINPROGRESS 情况的方式,还是使用非阻塞套接字进行连接。

来自 connect() 的 Linux documentation :

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 - 套接字连接结束,操作正在非阻塞套接字上进行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48474935/

相关文章:

附加字符后无法释放分配的字符串内存

c++ - Qt5 QProcess 处理带有 "special"字符的参数

linux - 使用 pip 安装 docker-cloud 客户端

java - 将视频流从 Socket 保存到文件

c - 在C、linux中通过poll fd获取unix socket连接是否需要额外的参数或设置?

c - 使用String函数不输出Using Arduino

c - 了解 memcpy() 的源代码

c - 有没有办法在编译时将初始化结构的数据插入到另一个相同类型的结构中?

linux - Jenkins 执行 bash shell 命令

python - Gunicorn - Unix 套接字从何而来?