简体   繁体   中英

Are Linux socket file descriptors generally suitable for hashing

I am programming a Linux multi-user server, and each connection accepted returns an int containing the socket file descriptor for that connection. I also have one UserConnection object corresponding to each connection. I am using a hash table (C++ STL unordered_map<int, UserConnection> ) to store key-value pairs of socket file descriptors (keys) and UserConnection objects (values).

Is it safe to put socket file descriptors as keys in a hash table? Is there any pattern in Linux's socket number allocation that might not work well with the hashing function?

The manual page for open(2) explictly states that the lowest unused file descriptor is assigned to the new file descriptor:

The file descriptor returned by a successful call will be the lowest-numbered file descriptor not currently open for the process.

Similar verbiage appears to be missing from socket(2) , but I think this is a fairly safe assumption -- that the same applies to socket as well.

It then follows that creating sockets will result in monotonically increasing file descriptors, for the new sockets, which will be reused at the first opportunity. As such, this is the ideal use case for hashing.

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