Is it possible to attach application data to a socket?

118 Views Asked by At

I'm developing an event driven Win32 socket server in C. In order to control several aspects of the communication process, I need to create a data structure at the moment in which a new connection is accepted, however I haven't found a way to attach my application's data to the newly accepted socket in such a way that by knowing the socket I can efficiently retrieve the connection control data, because of that, every time I receive a FD_READ or FD_CLOSE message I must perform a search operation, but even though the search function is very efficient it still implies an overhead.

I wonder if there is a set of functions similar to SetWindowLongPtr/GetWindowLongPtr which could allow me to attach my application's data to every new socket, that way I could avoid the search operation completely.

CLARIFICATION:

I am not looking for a more efficient way to search, the one I'm using is quite efficient, what I want is a way to completely avoid any kind of search operation (if such a thing is possible).

1

There are 1 best solutions below

1
On BEST ANSWER

To avoid having to lookup the socket data each time, switch to an I/O Completion Port:

Windows Sockets 2.0: Write Scalable Winsock Apps Using Completion Ports

Create an IOCP with CreateIoCompletionPort() and associate each accepted socket with it, then perform asynchronous socket I/O operations using WSASend() and WSARecv(), which allow you to pass a custom data pointer with each operation. Define and allocate a custom struct for that purpose. Then call GetQueuedCompletionStatus() periodically, such as in a worker thread, and each IOCP notification will give you the struct pointer that was associated with the socket operation that completed.