检测连接是否已建立
我最近开始学习 Linux 下的网络编程,似乎我无法找出检测是否已建立与远程主机的连接的正确方法。 ATM所有未建立的连接都注册在一个epoll实例中。一旦 EPOLLOUT 标志设置为 1 的事件到达,连接将被标记为已建立。就这么简单,但我做得对......
有更好的方法吗?如果不是,等待套接字变得可写是否是保证连接已建立的好方法?
I recently began learning network programming under Linux and it seems I can't figure out the right way to detect if a connection to remote host has been established. ATM all non-established connections are registered in a epoll instance. Once an event with the EPOLLOUT flag set to 1 arrives, the connection is marked as established. As easy as this, but I'm doing this right ...
Is there a better way of doing this? And if not, does waiting on a socket to become writeable is a good way to guarantee that connection has been established?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
poll/epoll/select 应该都可以工作。的手册页
connect(2) 表示您得到 EINPROGRESS,并且您可以使用 select 检测完成情况或轮询以检查它是否可写。然后使用getsockopt检查SOL_SOCKET、SO_ERROR状态,看看连接是成功还是失败。
如果您在连接仍在尝试时重试连接,则您会得到 EALREADY。
所以这是有记录的方法,对我来说听起来很正确。
poll/epoll/select should all work. The man-page for
connect(2) says you get EINPROGRESS, and that you can detect completion by using select or poll to check for it to become writable. Then use getsockopt to check the SOL_SOCKET, SO_ERROR status, to see if connect succeeded or failed.
If you retry connect while it's still trying, you get EALREADY.
So this is the documented way to do it, and sounds right to me.