How does two sockets on same address and port work?

For some limit of my design, I create and bind two sockets on same IP address and same port, each of the socket is created and bound in one process, using the socket option of SO_REUSEADDR . And my operating system doesn´t support child process or thread. I am using a IP stack based on BSD. I want the process with the first socket to be a packet sender and the process with the second socket to be a listener with a infinite loop of recv() called.
My assumption is that the both of the sockets can send packets to the remote address and the second bound socket can receive the packets from remote. But the result is that, the second socket can receive packets untill the first socket sends a packet out. After that, it seems that the sockets are switched, the second socket is inactive and can´t receive anything.
I am wondering if this is the correct behavior of BSD socket? And how sendto() function impact the BSD changing the socket configuration/setting for the sockets?
 
Thats normal behavior. SO_REUSEADDR is not for having several sockets working with same address but for fast socket rebinding in case the first socket was not closed when its process crashed or hanged and you need to attach another socket on the fly for less downtime. The net stack switches the sockets on activity, you cant actually have two sockets binded to same address.
 
Is poll or recvfrom also a kind of activity?

I am the activity which can switch the sockets in this case.
 
To be more specific, do not use sockets like that. What is your operating system? If it is POSIX friendly you should be able to share same socket descriptor between different processes and then use either signals or some other IPC method to synchronize.
 
No, you do not need to fork. Spawn two processes. Make first process create and bind a socket and save the descriptor to file (or put it in shared memory or any other method to share data between processes). Second process can just read descriptor "id", assign it to a local variable and use it normally.
 
Thanks! it sounds good! but still have questions for this. The file descriptor is only valid in one process if I understand correctly, how does the "id" from one process work in another independent process? Wish I can have some example if possible.
 
Every process has its own file descriptor table, does it mean the id of the FD is only the index in the table and this number won't work in other's table?
 
FD is an index in kernel's relational array to objects (also known as file descriptor table). So its not something binded to a single process or based on process heap or stack. Or at least it is so on POSIX(like/compatible) operating systems.
 
Good to know, I chose the design like this because I thought I can't just give the FD to anther process directly.
I will verify this in my system tommorrow and report the result.
Tack!
 
Back
Top