IP address change notification

When writing a code that bind() to a specific IP address, it is important to know when the IP address assigned by DHCP, has changed. IPHLPAPI provides an API to notify the IP address change, as NotifyAddrChange(). In this page, usage of NotifyAddrChange() is shown.

Sample code

The following sample code shows how to use NotifyAddrChange().


#include <stdio.h>
#include <windows.h>

#include <winsock2.h>
#include <iphlpapi.h>

int
main()
{
 OVERLAPPED overlap;
 DWORD ret;

 HANDLE hand = WSACreateEvent();
 overlap.hEvent = WSACreateEvent();

 ret = NotifyAddrChange(&hand, &overlap);

 if (ret != NO_ERROR) {
   if (WSAGetLastError() != WSA_IO_PENDING) {
     printf("NotifyAddrChange error...%d\n", WSAGetLastError());
     return 1;
   }
 }

 if (WaitForSingleObject(overlap.hEvent, INFINITE) == WAIT_OBJECT_0) {
   printf("IP Address table changed.\n");
 }

 return 0;
}

Sample code output

The sample will output an message like the following. Please note that this sample code will require an IP address change. An easy way to change the local IP address is using "ipconfig /release". Please try "ipconfig /release" while executing the sample code.


C:> a.exe
IP Address table changed.

Sample code 2

If you use NotifyAddrChange() with NULL arguments, NotifyAddrChange() will block until there is a change in the IP address table. When you want to create a thread that simply waits for an IP address to change, this might be useful.

The following sample shows how to use NotifyAddrChange(NULL,NULL). The output of this sample code will be the same as first sample code.


#include <stdio.h>

#include <winsock2.h>
#include <iphlpapi.h>

int
main()
{
 DWORD ret;

 ret = NotifyAddrChange(NULL, NULL);

 if (ret != NO_ERROR) {
   if (WSAGetLastError() != WSA_IO_PENDING) {
     printf("NotifyAddrChange error...%d\n", WSAGetLastError());
     return 1;
   }
 }

 printf("IP Address table changed.\n");

 return 0;
}

  

Copyright (C) GeekPage.JP. All rights reserved.