Dob Jenkins
Dob Jenkins

Reputation: 57

What happens to a socket that isn't explicitly closed? What if I make and connect to a new socket of the same parameters?

I am working with a piece of legacy C# code at the moment that does the following (modified for brevity):

var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, PortNumber);
clientSocket.Connect(ipEndPoint);
clientSocket.Receive(parameters);
clientSocket.Send(parameters);

ipAddress and Portnumber are generally the same (they'll rarely change, but they can and do occassionally). Notice that there is no Socket.Close, Socket.Disconnect, Socket.ShutDown, or using statement.

Also, the server code is pretty much the same except its looping through a if(socket.Poll()) {socket.accept();...} loop. It doesn't close or disconnect or shutdown either.

Hypothetically: What happens if I call this routine one time (keeping in mind the socket is not closed)?

What happens if I call this routine ten times, a second or two between each call?

Should I be 'closing' the socket, if so, how?

Thank you in advance!

Upvotes: 0

Views: 649

Answers (1)

dbush
dbush

Reputation: 225727

Since you're not specifying a local port when you initiate the connection, the OS will choose one for you when you make the connection. So each time you call this function, you get a new TCP connection to the remote server, each with a different local port.

Upvotes: 1

Related Questions