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

查看:106
本文介绍了如何找到在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);

要测试插座起来:

To test if the socket is up:

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));
}

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

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