Any threads can use any of the sockets inside a process. I can easily pass data to a socket from 2 threads interchangeably. I don't know the internals of current windows versions but I guess there is no such data stored for sockets. Probably there is only a lock (or maybe lockless data structure) to synchronize between multiple threads that try to access the same socket at the same time and that's it.
EDIT: In high performance network engines often a thread pool is used to serve sockets when an event occurs (incoming data available, or free space is available in the send buffer, incoming connection, ...) with one of the sockets and something has to be done with the sockets, each time a random thread is used as a servant so finding out which thread handles the socket just makes no sense, its often random.
SubratSarkar wrote:
For my curiosity, how is a packet transferred from the port to thread ? Any article or referrer would be appreciated.
When the packet comes in on your ethernet card its header is parsed. If the target address isn't your machine then the packet is routed (if your machine is configured that way). If the target address is your machine then according to the target port number the incoming data is stored in the receive buffer (size of receive buffer is configurable with setsockopt/SO_RCVBUF) of the socket object inside the OS identified by the port.
Many processes can have an open handle that reference the same socket object in the OS, and any thread of these processes that application can read out data from the receive buffer of the socket to the address space of the app. I myself never used a socket object from more than one processes but there is a function to duplicate socket handles:
WSADuplicateSocket[
^].
Summary: The address/port pair in the incoming packet identifies a machine(address) and a socket object inside (port) the networking part of the OS. Any application can have an open handle to that socket object (the handle is basically a process-local "reference counting pointer" to an object inside the OS) and any thread inside those applications can manipulate the socket object. When all applications close all handles to the socket object it might still remain alive for some time if it has data to send in its send buffer (search for socket linger to learn more about this) or unfinished tasks regarding the TCP protocol (shutdown, etc...).