c++ - How to avoid re-use socket? -


there server, there clients. clients connect server. servers function "accept" returns socket connected client. when client socket becomes invalid, can reused. how prevent server reuse same socket? p.s.: fans downvote pay attention, i'm not asking socket server, ask client sockets.

this clear misconceptions - i'm still voting question closed unless it's edited sensible.

but when client socket becomes invalid, can reused

no, socket file descriptor has closed if tcp connection has shut down. new socket allocated later new tcp connection, , receive file descriptor same integer value, isn't same socket.

the socket - not port, address.

no, socket handle process uses talk os tcp connection, uniquely identified 4-tuple consisting of 2 ports , 2 addresses. see this answer, i'm not going paste here.

if no connection, customer not aware of [closing socket]

if there no connection, there's nothing close.

if there existing tcp connection, , either client or server close socket, other end notified, , other end's socket become invalid (and should closed in response).

for example, socket have parameters so_reuseaddr , so_reuseport. why they?

when close connection, send packet telling other end of connection you've done so. after they've acknowledged this, receive other packets on same connection, if took different network path. so, tcp keeps closed connection around in time_wait state, preventing connection starting on same address:port tuple, arbitrary time until it's unlikely receive packet intended previous connection.

this arbitrary time_wait duration 4 minutes, long enough could, example, kill server process , restart (at point fail bind address:port, because closed connection still using address:port).

so_reuseaddr allows server replace old time_wait connection new, live connection.

so_reuseport allows multiple sockets bind to, , accept on, same port load-balancing purposes.

this documented, eg. in man page, , neither option has socket file descriptor value.

as bolov said in comment, reason these used server care address:port bound server, because that's how know reach it. local port of client connection assigned ephemeral port range, , no-one cares value except it's unique @ moment in time.


Comments

Popular posts from this blog

Hatching array of circles in AutoCAD using c# -

ios - UITEXTFIELD InputView Uipicker not working in swift -

Python Pig Latin Translator -