There's bunches of examples out there for you to google on, but basically the sequence is
int sfd = socket();
setcokopts( );
bind( );
If you carefully read the post , the above sequence WORKS just fine, that is NOT the issue. I do not see how setsockopt and its options allows for address reuse. That IS the issue.
I realize that I am NOT properly closing the the socket when I exit() the project during development.
The issue is when I rerun the project / application again the address remains in use. Irregardless of reason it remains in use - the setsockopt specifically have option to reuse the address - just for bind to reuse it.
And it does not. bind returns an error the "address already in use" and any further processing is useless.
Yes, I can try closing the socket, but that would defeat "address reuse " option.
listen(sfd, backlog);
for( ;; ) {
int connection = accept(sfd,
close(connection);
}
You don't need to call
bind()
more than once per open socket (sfd). In general, you will
fork()
or start a new thread to handle the new
connection
, so you can process the
backlog
quickly.