Recently I worked on a project, where I had to do some processing (reconnecting logic) whenever the IP address of the machine is changed. First, I felt that its going to be decently complex. But after a bit of R & D work, I came to know that it is surprisingly easy to do this with .NET! (such is the power of .NET Framework classes).
All I had to do was to register an event listener for the NetworkAddressChanged event (System.Net namespace). I did it on the application startup.
NetworkChange.NetworkAddressChanged += new System.Net.NetworkInformation.NetworkAddressChangedEventHandler(this.AddressChangedCallback);
Whenever the IP address of the machine is changed, the AddressChangedCallback() will be called. And thats it!
private void AddressChangedCallback(object sender, EventArgs e)
{
NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
foreach (NetworkInterface n in adapters)
{
System.Diagnostics.Trace.WriteLine(n.Name + " is " + n.OperationalStatus);
}
}
No comments:
Post a Comment