简体   繁体   中英

epoll - polling multiple file descriptors (that are sockets)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM