Reputation: 464
I am using TcpListener class to create a TCP socket on a certain IP and port in my machine. The code I use is as follows :
tcpListener = new TcpListener("192.168.0.110", 8005);
try
{
tcpListener.Start();
}
catch (Exception e)
{
Console.WriteLine(e);
return;
}
This works fine. I want to use a check thread to check the status of the listener.
private void CheckConnections()
{
while (true)
{
if (_tcpListener.Server.IsBound)
{
Console.WriteLine(_tcpListener.Active);
Console.WriteLine("IsBound : True");
}
else
{
Console.WriteLine(_tcpListener.Active);
Console.WriteLine("IsBound : False");
}
Thread.Sleep(2000);
}
}
When I change the IP of my machine manually from adapter settings, for example from "192.168.0.110" to "192.168.0.105", in the "netstat -ano" command I still see that the " 192.168.0.110:8005" is in Listening state. Also I could not find a way to subscribe to this change from my code. So my question is how to handle IP change on server side socket? Is there a way that I can get IP change information from the socket itself?
Upvotes: 0
Views: 483
Reputation: 11889
Sockets remain in listening state for a while after being closed. This is deliberate and is due to the way sockets have been designed. it doesn't mean your code is still listening, it means the O/S is listening and it will eventually go away.
As for the second part of the question, you can listen to the NotifyAddrChange notification, close your socket, and reopen on the new address.
Here is an article on how to do it. https://www.codeproject.com/Articles/35137/How-to-use-NotifyAddrChange-in-C
Upvotes: 1
Reputation: 109
I'm not sure if this is what you want.
Try to use TcpListener(IPAddress.Any, 8005);
This will accept any IPAddress so you don't have to change it on code everytime.
Unless you want to change it while the program is running, that will be a little bit more complicated. You would have to close the socket and change the IP.
Upvotes: 1