gpt4 book ai didi

linux - 为什么在电缆连接断开的情况下,socket send() 会返回成功代码?

转载 作者:太空宇宙 更新时间:2023-11-04 05:32:48 25 4
gpt4 key购买 nike

我通过 TCP 套接字连续发送数据包。然后,我拔掉网线,发现send()仍然返回成功。为什么?启动代码如下:

// This function must be called before any other functions called.
/* Return:
0: success
1: init socket fail
2: send fail
3: connect fail
*/

int mtMqttInit (const char *id, const char *username, const char *password, const char *hostName, const int tcpPort, unsigned int timeoutSec)
{
int pktLen;

mqtt_init(&mtBroker, id);
mqtt_init_auth(&mtBroker, username, password);

if (init_socket(&mtBroker, hostName, tcpPort)) {
if (debug)
printf ("init_socket()\n");
return MT_MQTT_INIT_SOCKET_FAIL;
}

if (mqtt_connect(&mtBroker) == -1) {
if (debug)
printf ("mqtt_connect()\n");
return MT_MQTT_INIT_CONNECT_FAIL;
}
.....
}

void mqtt_init(mqtt_broker_handle_t* broker, const char* clientid) {
// Connection options
broker->alive = 300; // 300 seconds = 5 minutes
broker->seq = 1; // Sequency for message indetifiers
// Client options
// .....
// Will topic
broker->clean_session = 1;
}

发送代码片段如下:

// Send the packet
log_status("to send");
if(broker->send(broker->socket_info, packet, sizeof(packet)) <
sizeof(packet)) {
log_error("send() failed");
return -1;
}
log_status("send() done");

即使电缆连接断开,我也看不到显示“send() faied”消息。也就是说,我无法确定套接字是否仍然有效。这是怎么回事?

最佳答案

我使用 getsockopt() 来检查套接字的有效性,而不是检查 send() 的返回值。有用。在知道套接字无效后,我关闭了它并重新创建。

代码来自 Simone,位于 How to find the socket connection state in C?

int error = 0;
socklen_t len = sizeof (error);
int retval = getsockopt (socket_fd, SOL_SOCKET, SO_ERROR, &error, &len);

/// ....
if (retval != 0) {
/* there was a problem getting the error code */
fprintf(stderr, "error getting socket error code: %s\n", strerror(retval));
return;
}

if (error != 0) {
/* socket has a non zero error status */
fprintf(stderr, "socket error: %s\n", strerror(error));
}

关于linux - 为什么在电缆连接断开的情况下,socket send() 会返回成功代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60486933/

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