挂在 connect()

Hang at connect()

所以,我有一个尝试连接服务器的客户端。 ip 和端口是从配置文件中检索的。如果配置文件中的某些内容不正确,我需要程序顺利失败。我使用以下代码连接到服务器

if (connect(sockfd, p->ai_addr, p->ai_addrlen) == -1)
{
    perror("client: connect");
    close(sockfd);
    continue;
}

如果用户尝试连接到不接受连接(即不存在)的子网上的服务器,则程序会失败并返回 No route to host。如果程序尝试连接到不在子网上的服务器(即配置错误),则程序会在 connect() 调用处挂起。我做错了什么?我需要它向用户提供应用程序失败的一些反馈。

通常我们不会在 if 语句中使用 continue,除非 if 语句在您没有显示的循环中。假设有一个外循环,这将对接下来发生的事情负责。要么继续重新进入 if 块(以尝试再次连接),要么跳过它。

另请注意,您正在 if 块内关闭 sockfd,因此如果您的循环重新进入 if 块进行重试,则需要创建一个新套接字首先.

我建议阅读一些客户端和服务器端套接字连接的示例代码,以更好地了解它的工作原理http://www.cs.rpi.edu/~moorthy/Courses/os98/Pgms/socket.html

如果全部失败,请提供 if 块周围的代码,并说明您希望如何 "fail smoothly"。失败的一种方法 "abruptly' would be to swap the continue statement with a call to exit() "-)

编辑:阅读 Barmar 的回答和他的评论后,您还需要注意这一点:

If the initiating socket is connection-mode, then connect() shall attempt to establish a connection to the address specified by the address argument. If the connection cannot be established immediately and O_NONBLOCK is not set for the file descriptor for the socket, connect() shall block for up to an unspecified timeout interval until the connection is established. If the timeout interval expires before the connection is established, connect() shall fail and the connection attempt shall be aborted.

还有..

If the connection cannot be established immediately and O_NONBLOCK is set for the file descriptor for the socket, connect() shall fail and set errno to [EINPROGRESS], but the connection request shall not be aborted, and the connection shall be established asynchronously. Subsequent calls to connect() for the same socket, before the connection is established, shall fail and set errno to [EALREADY]

当您说 "the program hangs" 时,您的意思是永远,还是可能用 TCP/IP 超时来解释的一段时间。

如果这和 Barmar 的答案仍然不够,那么按照建议查看周围的代码并确定是否被阻止或未被阻止等会有所帮助。

你没有做错任何事。 TCP 是为面对网络问题时的可靠性而设计的,因此如果它没有得到对其初始连接请求的响应,它会重试几次以防请求或响应在网络中丢失。 Linux 上的默认参数导致它需要大约一分钟才能放弃。然后它将报告失败并显示 Connection timed out 错误。

如果您想更快地检测到故障,请参阅C: socket connection timeout