epoll监听文件_epoll的 - 轮询多个文件描述符(即是插座)

I read the man page and went through this example for usage: https://banu.com/blog/2/how-to-use-epoll-a-complete-example-in-c/, but I can't figure a way to do what I am trying to do using epoll, can anyone lend me some help?

Basically I am writing a netcat type utility to better learn C/networking. I have created a basic server/client that can listen and connect on one port. Now I want to expand the server aspect to listen on a port range.

I plan to do this via a for loop for each port creating socket(), bind(), and listen().

Since port range can be up to 65k, I need to poll them and accept() when one has a connection request received.

Unlinke typical C servers that use poll or epoll to deal with multiple connections on one port, this is one connection on one of several thousand potential ports. I can't quite get from the examples how I could epoll the sockets and when a connection is requested accept it and unbind/stop listening/polling.

Has anyone got any example explanations/code to get me started please?

解决方案

1 - Create all your server sockets

2 - Their file descriptors will be contained in a range, something like [4, 199]

3 - Add all of them to the epoll descriptor, in a loop.

Then in the normal epoll loop, if the descriptor with the event is in the range of [4,199] or whatever was your range in practice, then you know it's a server socket and you need to accept on it, otherwise do whatever you do with your connected descriptor.

An alternative way of doing is to create 2 epoll descriptors, and use one just for the server sockets and the other just for the connected descriptors. The perk of this is that you'd need to use epoll on them both then! So I wouldn't advise this.

Since the number of descriptors you want to create is so big, you will most likely need to change some kernel parameter because you will probably hit some limit with so many open descriptors in a process.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值