TcpListener problem - re-binding to same port with different local addresses

Posted by Zvika on Stack Overflow See other posts from Stack Overflow or by Zvika
Published on 2009-09-21T12:27:32Z Indexed on 2010/06/12 10:12 UTC
Read the original article Hit count: 224

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about c#

Related posts about tcplistener