如何在C中找到套接字连接状态? [英] How to find the socket connection state in C?

查看:19
本文介绍了如何在C中找到套接字连接状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 TCP 连接.服务器只是从客户端读取数据.现在,如果连接丢失,客户端在将数据写入管道(损坏的管道)时会出错,但服务器仍然在该管道上侦听.有什么方法可以找到连接是否正常?

I have a TCP connection. Server just reads data from the client. Now, if the connection is lost, the client will get an error while writing the data to the pipe (broken pipe), but the server still listens on that pipe. Is there any way I can find if the connection is UP or NOT?

推荐答案

你可以像下面这样调用getsockopt:

You could call getsockopt just like the following:

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
", strerror(retval));
    return;
}

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

这篇关于如何在C中找到套接字连接状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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