我有一个小代理,应该不时连接到服务器
第一阶段它打开一个socket
:
const char* hostname // e.g. "127.0.0.1"
hostaddr = inet_addr(hostname);
/* Ultra basic "connect to port 22 on localhost"
* Your code is responsible for creating the socket establishing the
* connection
*/
sock = socket(AF_INET, SOCK_STREAM, 0);
sin.sin_family = AF_INET;
sin.sin_port = htons(22);
sin.sin_addr.s_addr = hostaddr;
if (connect(sock, (struct sockaddr*)(&sin),
sizeof(struct sockaddr_in)) != 0) {
fprintf(stderr, "failed to connect!\n");
return -1;
}
当 ip-address
无效,连接似乎挂起很长时间
失败之前
查看man page提供有关该主题的一些数据,但不提供如何超越它
我的问题是为什么以及如何为其添加超时(或任何其他解决方案)
最佳答案
引自其中一个答案here
Put the socket into non-blocking mode until you've connected, and then put it back into blocking mode once the connection's established.
关于c++ - 连接被拒绝后 connect() 长时间挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50999952/