Change IP address & Mask address (C++) Windows

Introduction

This is one way of changing IP address & mask address in C++ using Iphlpapi.h. It’s a simple program, no UI for you, sorry…

  • Use GetAdaptersInfo to get adapters information.
  • Then use GetPerAdapterInfo to get information for every ethernet network card. The information contains IP address.
  • Use DeleteIPAddress remove the old IP address.
  • Use AddIPAddress to add new IP&Mask address.
// ChangeIPAddress("192.168.0.123", "192.168.0.44","255,255,255,0");
bool ChangeIPAddress(char oldIPAddress[], char newIPAddress[], char newMaskAddress[])
{
    DWORD dwRetVal = 0;
    PIP_ADAPTER_INFO pAdapter = NULL;

    ULONG ulOutBufLen = sizeof(IP_ADAPTER_INFO);
    PIP_ADAPTER_INFO pAdapterInfo = (IP_ADAPTER_INFO *)malloc(sizeof(IP_ADAPTER_INFO));
    if (pAdapterInfo == NULL)
    {
        return false;
    }

    if (GetAdaptersInfo(pAdapterInfo, &ulOutBufLen) == ERROR_BUFFER_OVERFLOW)
    {
        free(pAdapterInfo);
        pAdapterInfo = (IP_ADAPTER_INFO *)malloc(ulOutBufLen);
        if (pAdapterInfo == NULL)
        {
            return false;
        }
    }

    if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR)
    {
        pAdapter = pAdapterInfo;
        while (pAdapter)
        {
            if (strcmp(oldIPAddress, pAdapter->IpAddressList.IpAddress.String) == 0)
            {
                IPAddr addr = inet_addr(newIPAddress);
                IPMask mask = inet_addr(newMaskAddress);
                ULONG context, instance;

                if (DeleteIPAddress(pAdapter->IpAddressList.Context) != NO_ERROR
                    || AddIPAddress(addr, mask, pAdapter->Index, &context, &instance) != NO_ERROR)
                {
                    return false;
                }
                return true;
            }
            pAdapter = pAdapter->Next;
        }
        return false;
    }
}

3 thoughts on “Change IP address & Mask address (C++) Windows”

  1. Sorry, but your code is not worked, and always return false. My IP cmd>ipconfig is still old.

Comments are closed.