tags:

views:

253

answers:

1

I'm trying to do the following: listen on some port for loopback connections only, and then start listening on any IP address. Here is the code:

TcpListener l1 = new TcpListener(new IPEndPoint(IPAddress.Loopback, 12345));
l1.Start();
Socket s = l1.AcceptSocket();
Console.ReadKey();
//s.Close();
l1.Stop();
TcpListener l2 = new TcpListener(new IPEndPoint(IPAddress.Any, 12345));
l2.Start();
l2.AcceptSocket();
Console.ReadKey();

The problem is that if a client connects while listening on the Loopback address (l1), then no other client can connect to the Loopback address when the second listener (l2) starts listening. why is that?

Another thing I noticed is that if I close all clients that connected to l1 (the remarked line), then l2 does accept loopback connections.

Any ideas?

+1  A: 

Stop() method doesn't close any connections. So, you'd better bind to Any interface and then process data depending on connection IP address.

FractalizeR
I would like to avoid listening on the Any interface and then discriminate connections. I need the two stages: Loopback then Any.Why does TcpListener.Stop() on the first listener doesn't allow the second listener to accept Loopback connections if a client conected to the first listener?
Zvika
I don't see your point. How do you discriminate something? If you need to handle many connections at once, consider looking at some ready-to-use components like Indy Sockets.
FractalizeR
This is not the issue. I'm asking a technical question, a windows internals question on the behavior of listening sockets. Listening on the Loopback interface, closing it, and then listening on Any interface.
Zvika