0

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?

I.K.
  • 414
  • 6
  • 18

2 Answers2

1

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.

hamon
  • 103
  • 3
  • 9
  • Thanks. I am actually trying to "handle" IP change that is caused by other reasons rather than my program. If the IP address changes I need to be aware of that and inform the user about it. Because to clients of that TcpListener will not be able to reach it anymore. – I.K. Aug 11 '20 at 12:31
  • Try to use this: https://stackoverflow.com/questions/6803073/get-local-ip-address after and before, store it in a variable. and create a if running the background – hamon Aug 11 '20 at 12:34
1

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

Neil
  • 11,059
  • 3
  • 31
  • 56
  • 1
    By the help of this comment, i decided to subscribe to NetworkChange.NetworkAddressChanged event and handle the IP change there. Thanks for help! – I.K. Aug 11 '20 at 13:31