确定一个TCP套接字的状态 [英] Determine the state of a TCP socket

查看:665
本文介绍了确定一个TCP套接字的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始了解如何在C ++中一个TCP服务器/客户端实现(在Windows和Linux)。
在这一刻,我实现服务器(和使用telnet客户端作为测试)。
服务器应用程序发送和像一个魅力recieving数据。(我将实现客户了解所有的服务器端之后)。
但我需要找到一个纲领性(C ++或OS API)的方式来查询TCP套接字状态(ESTABLISHED,FIN_WAIT_2,CLOSE_WAIT等),而不使用write()/的recv()来处理错误例外..

I'm starting to learn about how to implement in C++ a TCP server/client (on Windows and Linux). At this moment, I'm implementing the server (and testing with the telnet as client). The server application is sending and recieving data like a charm.. (I will implement the client after understand all the server side). But I need to find a programmatic (C++ or O.S API) way to query the TCP socket state (ESTABLISHED, FIN_WAIT_2, CLOSE_WAIT, etc..) without use the write()/recv() to handle the error exception..

例如:


  1. 服务器启动时,绑定套接字,等待连接

  2. 系统客户端启动并连接在服务器上

  3. 在这里,我必须在使用该FUNC服务器循环ioctlsocket(插座,FIONREAD,pbytes_available),确定当我有数据读取。

  4. 如果客户端发送一些数据,然后在pbytes_available会> 1和服务器使用的recv()来获得。

  5. 如果客户端不发出任何东西,然后服务器可以执行其他任务,并检查是否有下一个循环的插座上的数据。

  6. 如果我关闭Telnet(客户端程序),然后运行netstat的,我会看到服务器插槽与CLOSE_WAIT状态,所以我需要在服务器端关闭套接字..

这就是问题:如何查询TCP套接字状态,以确定我需要关闭此会话吗? (不使用send()/ recv的(),像netstat的做)

And this is the question: How can I query the TCP socket state to determine that I need close this session? (without use the send()/recv(), like the "netstat" do)

注意:我试过的getsockopt(插座,SOL_SOCKET,SO_ERROR,&安培; optval的,和放大器; optlen),但它返回0时的状态为ESTABLISHED / CLOSE_WAIT和optval的也没有变化。

Note: I tried the "getsockopt(socket, SOL_SOCKET, SO_ERROR, &optval, &optlen )", but it return 0 when the state is ESTABLISHED/CLOSE_WAIT and the "optval" also doesn't changes.

推荐答案

与阻塞模式插座通常的方法是奉献一个线程读取插槽。当的recv()返回0,这意味着对方已经关闭了连接和端口的现在是 CLOSE_WAIT 状态。

The usual technique with blocking-mode sockets is to dedicate a thread to reading the socket. When recv() returns 0 it means the peer has closed the connection and the port is now in CLOSE_WAIT state.

另外,您可以使用选择()和朋友,告诉你,当插座是可读的,其中包括情况下的recv()将返回零。使用 FIONREAD 作为轮询机制确实是pretty没用,因为它不包括这种情况。

Alternatively you can use select() and friends to tell you when the socket is readable, which includes the case where recv() will return zero. Using FIONREAD as a polling mechanism is really pretty useless as it doesn't cover this case.

这篇关于确定一个TCP套接字的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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