Renewing IP address using DHCP

In this page, usage of IpRenewAddress() is shown. Using IpRenewAddress(), code that acts like "ipconfig /renew" can be created.

Sample code

The following sample code shows how to use IpRenewAddress(). The following sample renews IP address assigned to every network interface. The following sample works like the command "ipconfig /renew".

List of network interfaces can be obtained using GetInterfaceInfo(). IpRenewAddress() uses the network adapter structure which can be obtained by GetInterfaceInfo().


#include <stdio.h>

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

int
main()
{
 int i;
 PIP_INTERFACE_INFO pInfo = NULL;
 ULONG ulOutBufLen = 0;
 DWORD dwRetVal = 0;

 /* Get ulOutBufLen size. */
 if (GetInterfaceInfo(NULL, &ulOutBufLen)
       == ERROR_INSUFFICIENT_BUFFER) {
   pInfo = (IP_INTERFACE_INFO *) malloc (ulOutBufLen);
 }

 /* Get the actual data. */
 dwRetVal = GetInterfaceInfo(pInfo, &ulOutBufLen);

 if (dwRetVal == NO_ERROR ) {
   printf("Number of Adapters: %ld\n\n", pInfo->NumAdapters);

   for (i=0; i<pInfo->NumAdapters; i++) {
     printf("Adapter Name: %ws\n", pInfo->Adapter[i].Name);
     printf("Adapter Index: %ld\n", pInfo->Adapter[i].Index);

     if (IpRenewAddress(&pInfo->Adapter[i]) == NO_ERROR) {
      printf("renewed\n");
     } else {
      printf("renew failed\n");
     }

     printf("\n");
   }
 } else {
   printf("GetInterfaceInfo failed.\n");
   LPVOID lpMsgBuf;
		
   if (FormatMessage(
           FORMAT_MESSAGE_ALLOCATE_BUFFER | 
           FORMAT_MESSAGE_FROM_SYSTEM | 
           FORMAT_MESSAGE_IGNORE_INSERTS,
           NULL,
           dwRetVal,
           MAKELANGID(LANG_NEUTRAL,
                      SUBLANG_DEFAULT), /* Default language */
           (LPTSTR) &lpMsgBuf,
           0,
           NULL ))  {
     printf("Error: %s", lpMsgBuf);
   }

   LocalFree( lpMsgBuf );
 }

 return 0;
}

Sample code output

The sample will output an message like the following.


C:> a.exe
Number of Adapters: 2

Adapter Name: \DEVICE\TCPIP_{22EXXC3D-F01D-4231-AE59-C23EXXXX6C66}
Adapter Index: 2
renewed

Adapter Name: \DEVICE\TCPIP_{4E7XX61B-836C-49AB-8B02-775BXXXX7352}
Adapter Index: 3
renewed

  

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