Releasing DHCP oriented IP address
In this page, usage of IpReleaseAddress() is shown. Using IpReleaseAddress(), code that acts like "ipconfig /release" command can be created.
Sample code
The following sample code shows how to use IpReleaseAddress(). The following sample releases the IP address assigned to all the network interfaces. The following sample works like the command "ipconfig /release".
List of network interfaces can be obtained using GetInterfaceInfo(). IpReleaseAddress() 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 (IpReleaseAddress(&pInfo->Adapter[i]) == NO_ERROR) {
printf("released\n");
} else {
printf("release 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
released
Adapter Name: \DEVICE\TCPIP_{4E7XX61B-836C-49AB-8B02-775BXXXX7352}
Adapter Index: 3
released