CNotifyAddrChange C# class uses a Thread, AutoResetEvents, and an Event Handler in conjunction with the Microsoft's IP Helper API (Iphlpapi.dll)
NotifyAddrChange function to notify you if an IP address has changed.
The demo download is a VS 2008 C# Windows Forms application that demonstrates the use of the
Being fairly new to the C# / .NET world, I knew I wanted to use the Iphlpapi.dll
NotifyAddrChange function to find out when an IP address has changed and how to do it in C++, but I could not find anything on how to do it in C#. The
CNotifyAddrChange class represents my solution to the problem.
Using the code
Declare an instance of the
CNotifyAddrChange object in the scope within you want it to survive.
public partial class Main : Form
protected CNotifyAddrChange m_oNotifyAddrChange = null;
Create the EventHandler you want called when an IP address has changed.
public void OnAddrChangedEvent(object sender, EventArgs e)
The class will auto start when it is allocated, and it has a
Start() procedure which you can call to start it manually:
private void Start_Click(object sender, EventArgs e)
if (m_oNotifyAddrChange == null)
m_oNotifyAddrChange = new CNotifyAddrChange();
m_oNotifyAddrChange.AddrChangedEvent += OnAddrChangedEvent;
There is a
Stop() procedure that you can use to stop it from monitoring for changes.
private void Stop_Click(object sender, EventArgs e)
if (m_oNotifyAddrChange != null)
Points of interest
Tricks to calling the NotifyAddrChange API function
NotifyAddrChange function takes a pointer to an
OVERLAPPED object. Rather than re-creating this structure yourself, it is recommended that you use the .NET
NativeOverlapped class. Then, you have to set the EventHandle inside of the
OVERLAPPED object, which is an
IntPtr. There is no proper cast from the
AddrChangeEvent, so the best way to get the
IntPtr was to use the
AutoResetEvent AddrChangeEvent = new AutoResetEvent(false);
NativeOverlapped oOverlapped = new NativeOverlapped();
IntPtr pnHandle = IntPtr.Zero;
UInt32 nRetVal = NotifyAddrChange(ref pnHandle, ref oOverlapped);
if(nRetVal == 997)
- 2009-04-07: Initially published.