Most of the time, ipconfig, netsh or ip addr is the right way to change an IP address. But installers, device-setup tools, test harnesses and network appliances often need to do it from code: read the current configuration, add an address to an adapter and remove it again, with proper error handling instead of a parsed shell command.
This guide builds a small C++17 library and a command-line tool, ipaddr, that do exactly that on Windows (with the IP Helper API) and Linux (with getifaddrs and rtnetlink). Both platforms share one interface and one address parser, so the code that matters to the rest of a program is the same everywhere. A test adds and removes real addresses on the loopback interface. Everything was built and tested with GCC and Clang (C++17 and C++20, warnings as errors, sanitizers on) and with MSVC on Windows 11, including a test that adds and removes real IPv4 and IPv6 addresses.
The Short Answer
How do I change an IP address in C++ on Windows? Call CreateUnicastIpAddressEntry to add an address to an adapter and DeleteUnicastIpAddressEntry to remove one. List adapters and their addresses with GetAdaptersAddresses. All three are in the IP Helper API (iphlpapi.lib), and the first two need administrator rights.
And on Linux? Send an RTM_NEWADDR or RTM_DELADDR message on a netlink socket, which is what ip addr add does. List addresses with getifaddrs. Changing addresses needs root or the CAP_NET_ADMIN capability.
Is the change permanent? No. On both systems an address added this way is lost at the next restart. A permanent static address belongs in the system’s network configuration (netsh, New-NetIPAddress, NetworkManager, netplan or systemd-networkd).
What Changing an IP Configuration Means
An IP configuration is the set of addresses a network interface answers to, each with a prefix length that says how much of the address names the network, plus the default gateway and DNS servers. “Changing the IP address” in code usually means adding a new address to an interface and removing the old one; an interface can hold several addresses at once.
Four terms come up throughout:
- Interface (adapter). A network connection the operating system knows about: an Ethernet port, a Wi-Fi card, a VPN, the loopback interface. Each has a name (“Ethernet”, “eth0”) and a numeric index. The index is what the APIs take, but it can change when an adapter is disabled and re-enabled, so the tool here accepts either.
- Address with prefix length.
192.168.1.50/24means the address 192.168.1.50 in a network whose first 24 bits are fixed. The same thing written the old way is a subnet mask:/24is255.255.255.0. - Unicast address. An address that belongs to one interface, as opposed to multicast or broadcast addresses. These are the addresses you add and remove.
- Persistent vs active configuration. The active configuration is what the network stack is using now. The persistent configuration is what it loads at boot. The APIs in this guide change only the active one.
The Tools First: Commands That Do the Same Job
Before writing code, it helps to know the commands your program is replacing. They are also the quickest way to check what your code did.
| Task | Windows (Command Prompt or PowerShell) | Linux |
|---|---|---|
| List interfaces and addresses | ipconfig /all or Get-NetIPAddress | ip addr |
| Add an address (until restart) | New-NetIPAddress -InterfaceAlias Ethernet -IPAddress 192.168.1.60 -PrefixLength 24 -PolicyStore ActiveStore | ip addr add 192.168.1.60/24 dev eth0 |
| Remove an address | Remove-NetIPAddress -IPAddress 192.168.1.60 | ip addr del 192.168.1.60/24 dev eth0 |
| Add a permanent static address | netsh interface ipv4 add address "Ethernet" 192.168.1.60 255.255.255.0 | Your distribution’s network configuration |
| API used in this guide | GetAdaptersAddresses, CreateUnicastIpAddressEntry, DeleteUnicastIpAddressEntry | getifaddrs, RTM_NEWADDR, RTM_DELADDR |
If a program only ever needs to run one of these commands once, running the command is fine. Code earns its place when the program has to decide what to change based on what it finds, report precise errors or run without a shell.
Addresses, Prefixes and Subnet Masks in C++
Both platforms hand over addresses as raw bytes inside sockaddr structures. Everything a person types or reads is text. The ip_text module converts between the two, with no operating system headers, so the same code and the same tests run everywhere:
parse_addressandparse_prefixaccept192.168.1.50,192.168.1.50/24,fd00::5andfd00::5/64. Without a/n, the prefix is the full length: one single address.address_to_stringprints IPv4 in dotted decimal and IPv6 in the canonical form from RFC 5952: lower case, no leading zeros and the longest run of zero groups shortened to::.ipv4_maskandprefix_from_ipv4_maskconvert between/24and255.255.255.0, and reject a “mask” such as255.0.255.0whose one bits are not contiguous.
// ip_text.h - IPv4 and IPv6 addresses with a prefix length, as text and as
// bytes. No operating system headers: the same code runs on Windows and Linux.
#pragma once
#include <array>
#include <cstdint>
#include <optional>
#include <string>
#include <string_view>
enum class Family { IPv4, IPv6 };
struct IpPrefix {
Family family = Family::IPv4;
std::array<std::uint8_t, 16> bytes{}; // IPv4 uses the first 4
int prefix_length = 0; // 0-32 for IPv4, 0-128 for IPv6
std::size_t size() const { return family == Family::IPv4 ? 4 : 16; }
int max_prefix() const { return family == Family::IPv4 ? 32 : 128; }
};
// "192.168.1.50" or "fd00::1". Leading zeros in IPv4 parts are rejected,
// because some tools read "010" as octal 8.
std::optional<IpPrefix> parse_address(std::string_view text);
// "192.168.1.50/24" or "fd00::1/64". Without "/n", the prefix is the full
// length (/32 or /128), which means "this one address".
std::optional<IpPrefix> parse_prefix(std::string_view text);
// "192.168.1.50", or IPv6 in the canonical RFC 5952 form: lower case, no
// leading zeros, the longest run of two or more zero groups written as "::".
std::string address_to_string(const IpPrefix& ip);
std::string prefix_to_string(const IpPrefix& ip); // with "/n"
// 24 -> "255.255.255.0". Defined for 0-32 only.
std::string ipv4_mask(int prefix_length);
// "255.255.255.0" -> 24. Empty for a mask whose one bits are not contiguous.
std::optional<int> prefix_from_ipv4_mask(std::string_view mask);
// "00-15-5D-01-02-03", the format ipconfig uses.
std::string mac_to_string(const std::uint8_t* bytes, std::size_t length);
Two choices in the parser are deliberate. It rejects IPv4 parts with leading zeros, because some tools read 010 as octal 8, and it rejects a prefix length with a leading zero (/08). Both are cheap ways to stop a typo from silently becoming a different address.
The implementation is plain string handling:
#include "ip_text.h"
#include <cstdio>
namespace {
std::optional<unsigned> parse_decimal(std::string_view s, unsigned max)
{
if (s.empty() || s.size() > 3 || (s.size() > 1 && s[0] == '0'))
return std::nullopt;
unsigned value = 0;
for (char c : s) {
if (c < '0' || c > '9')
return std::nullopt;
value = value * 10 + static_cast<unsigned>(c - '0');
}
if (value > max)
return std::nullopt;
return value;
}
bool parse_ipv4(std::string_view s, std::uint8_t* out)
{
for (int part = 0; part < 4; ++part) {
const std::size_t dot = s.find('.');
const bool last = part == 3;
if (last != (dot == std::string_view::npos))
return false; // need exactly three dots
const auto value = parse_decimal(s.substr(0, dot), 255);
if (!value)
return false;
out[part] = static_cast<std::uint8_t>(*value);
if (!last)
s.remove_prefix(dot + 1);
}
return true;
}
std::optional<unsigned> parse_hex_group(std::string_view s)
{
if (s.empty() || s.size() > 4)
return std::nullopt;
unsigned value = 0;
for (char c : s) {
unsigned digit;
if (c >= '0' && c <= '9') digit = static_cast<unsigned>(c - '0');
else if (c >= 'a' && c <= 'f') digit = static_cast<unsigned>(c - 'a' + 10);
else if (c >= 'A' && c <= 'F') digit = static_cast<unsigned>(c - 'A' + 10);
else return std::nullopt;
value = value * 16 + digit;
}
return value;
}
// Splits "a:b:c" into groups; an empty string gives no groups.
bool parse_groups(std::string_view s, unsigned* out, int& count)
{
count = 0;
if (s.empty())
return true;
for (;;) {
if (count == 8)
return false;
const std::size_t colon = s.find(':');
const auto group = parse_hex_group(s.substr(0, colon));
if (!group)
return false;
out[count++] = *group;
if (colon == std::string_view::npos)
return true;
s.remove_prefix(colon + 1);
}
}
bool parse_ipv6(std::string_view s, std::uint8_t* out)
{
unsigned head[8], tail[8];
int head_count = 0, tail_count = 0;
const std::size_t gap = s.find("::");
if (gap == std::string_view::npos) {
if (!parse_groups(s, head, head_count) || head_count != 8)
return false;
} else {
if (s.find("::", gap + 1) != std::string_view::npos)
return false; // "::" may appear only once
if (!parse_groups(s.substr(0, gap), head, head_count)
|| !parse_groups(s.substr(gap + 2), tail, tail_count)
|| head_count + tail_count > 7) // "::" stands for at least one group
return false;
}
unsigned groups[8] = {};
for (int i = 0; i < head_count; ++i)
groups[i] = head[i];
for (int i = 0; i < tail_count; ++i)
groups[8 - tail_count + i] = tail[i];
for (int i = 0; i < 8; ++i) {
out[2 * i] = static_cast<std::uint8_t>(groups[i] >> 8);
out[2 * i + 1] = static_cast<std::uint8_t>(groups[i] & 0xFF);
}
return true;
}
} // namespace
std::optional<IpPrefix> parse_address(std::string_view text)
{
IpPrefix ip;
if (text.find(':') != std::string_view::npos) {
ip.family = Family::IPv6;
if (!parse_ipv6(text, ip.bytes.data()))
return std::nullopt;
} else if (!parse_ipv4(text, ip.bytes.data())) {
return std::nullopt;
}
ip.prefix_length = ip.max_prefix();
return ip;
}
std::optional<IpPrefix> parse_prefix(std::string_view text)
{
const std::size_t slash = text.find('/');
auto ip = parse_address(text.substr(0, slash));
if (!ip || slash == std::string_view::npos)
return ip;
const auto length = parse_decimal(text.substr(slash + 1), static_cast<unsigned>(ip->max_prefix()));
if (!length)
return std::nullopt;
ip->prefix_length = static_cast<int>(*length);
return ip;
}
std::string address_to_string(const IpPrefix& ip)
{
char buffer[48];
if (ip.family == Family::IPv4) {
std::snprintf(buffer, sizeof buffer, "%u.%u.%u.%u", ip.bytes[0], ip.bytes[1], ip.bytes[2], ip.bytes[3]);
return buffer;
}
unsigned groups[8];
for (int i = 0; i < 8; ++i)
groups[i] = static_cast<unsigned>(ip.bytes[2 * i] << 8 | ip.bytes[2 * i + 1]);
int best_start = -1, best_length = 1; // a single zero group is not compressed
for (int i = 0; i < 8;) {
int j = i;
while (j < 8 && groups[j] == 0)
++j;
if (j - i > best_length) {
best_start = i;
best_length = j - i;
}
i = (j == i) ? i + 1 : j;
}
std::string out;
for (int i = 0; i < 8; ++i) {
if (i == best_start) {
out += "::";
i += best_length - 1;
continue;
}
if (!out.empty() && out.back() != ':')
out += ':';
std::snprintf(buffer, sizeof buffer, "%x", groups[i]);
out += buffer;
}
return out;
}
std::string prefix_to_string(const IpPrefix& ip)
{
return address_to_string(ip) + "/" + std::to_string(ip.prefix_length);
}
std::string ipv4_mask(int prefix_length)
{
const std::uint32_t mask = prefix_length == 0 ? 0 : ~std::uint32_t{0} << (32 - prefix_length);
IpPrefix ip;
for (int i = 0; i < 4; ++i)
ip.bytes[static_cast<std::size_t>(i)] = static_cast<std::uint8_t>(mask >> (24 - 8 * i));
return address_to_string(ip);
}
std::optional<int> prefix_from_ipv4_mask(std::string_view mask)
{
const auto ip = parse_address(mask);
if (!ip || ip->family != Family::IPv4)
return std::nullopt;
const std::uint32_t bits = std::uint32_t{ip->bytes[0]} << 24 | std::uint32_t{ip->bytes[1]} << 16
| std::uint32_t{ip->bytes[2]} << 8 | ip->bytes[3];
int length = 0;
while (length < 32 && (bits & (std::uint32_t{1} << (31 - length))))
++length;
// Every bit after the first zero must be zero too: 255.0.255.0 is not a mask.
const std::uint32_t expected = length == 0 ? 0 : ~std::uint32_t{0} << (32 - length);
if (bits != expected)
return std::nullopt;
return length;
}
std::string mac_to_string(const std::uint8_t* bytes, std::size_t length)
{
std::string out;
char buffer[4];
for (std::size_t i = 0; i < length; ++i) {
std::snprintf(buffer, sizeof buffer, i == 0 ? "%02X" : "-%02X", bytes[i]);
out += buffer;
}
return out;
}
The test for this file checks fixed answers, then feeds 15 valid and invalid strings to both parse_address and the operating system’s own inet_pton and inet_ntop, and requires the same verdict and the same canonical text. It runs on both platforms, so Windows and Linux agree with the parser too.
| Prefix length | Subnet mask | Addresses in the network |
|---|---|---|
| /8 | 255.0.0.0 | 16,777,216 |
| /16 | 255.255.0.0 | 65,536 |
| /20 | 255.255.240.0 | 4,096 |
| /24 | 255.255.255.0 | 256 |
| /30 | 255.255.255.252 | 4 |
| /32 | 255.255.255.255 | 1 (a single address) |
One Interface for Windows and Linux
The rest of the program sees one small header. Each platform gets its own .cpp file, and CMake picks the right one:
// interfaces.h - list network interfaces and add or remove IP addresses.
// One interface, two implementations: interfaces_windows.cpp (IP Helper API)
// and interfaces_linux.cpp (getifaddrs and rtnetlink).
#pragma once
#include "ip_text.h"
#include <string>
#include <vector>
struct Interface {
std::string name; // "Ethernet" on Windows, "eth0" on Linux
unsigned index = 0; // the number the OS uses to identify it
std::string mac; // empty when the interface has none
bool up = false;
bool loopback = false;
std::vector<IpPrefix> addresses; // every unicast address, with its prefix length
};
// Every interface on this computer. On failure, returns an empty list and
// sets error to an OS error code.
std::vector<Interface> list_interfaces(int& error);
// Adds or removes one address. Both return 0 on success, otherwise an OS
// error code (a Windows error code, or an errno value on Linux).
// Both need administrator rights (Windows) or CAP_NET_ADMIN (Linux).
int add_address(unsigned interface_index, const IpPrefix& address);
int remove_address(unsigned interface_index, const IpPrefix& address);
// The meaning of the codes that callers need to tell apart.
bool is_access_denied(int error);
bool is_already_present(int error);
bool is_not_found(int error);
bool is_not_supported(int error); // e.g. IPv6 is disabled on this system
// "error 5 (access denied)": the number, plus a short English description
// for the common cases. Not localized, so test output stays the same everywhere.
std::string error_text(int error);
Errors are returned as plain OS error codes (a Windows error code or a Linux errno value) rather than thrown. The callers that need to react to a specific failure ask is_access_denied, is_already_present, is_not_found or is_not_supported, so no platform constants leak into portable code.
Windows: Listing Adapters with GetAdaptersAddresses
GetAdaptersAddresses returns a linked list of adapters, each with its unicast addresses, prefix lengths, MAC address, type and status, for IPv4 and IPv6 together. It supersedes the IPv4-only GetAdaptersInfo, which Microsoft’s documentation has recommended against since Windows XP.
// interfaces_windows.cpp - Windows implementation with the IP Helper API:
// GetAdaptersAddresses to list, CreateUnicastIpAddressEntry and
// DeleteUnicastIpAddressEntry to add and remove addresses.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <winsock2.h>
#include <ws2ipdef.h>
#include <iphlpapi.h>
#include <netioapi.h>
#include "interfaces.h"
#include <algorithm>
#include <cstring>
#include <vector>
namespace {
std::string to_utf8(const wchar_t* text)
{
const int size = WideCharToMultiByte(CP_UTF8, 0, text, -1, nullptr, 0, nullptr, nullptr);
if (size <= 1)
return {};
std::string out(static_cast<std::size_t>(size), '\0');
WideCharToMultiByte(CP_UTF8, 0, text, -1, &out[0], size, nullptr, nullptr);
out.pop_back(); // drop the terminating null
return out;
}
bool to_ip_prefix(const SOCKADDR* address, int prefix_length, IpPrefix& ip)
{
if (address->sa_family == AF_INET) {
ip.family = Family::IPv4;
std::memcpy(ip.bytes.data(), &reinterpret_cast<const sockaddr_in*>(address)->sin_addr, 4);
} else if (address->sa_family == AF_INET6) {
ip.family = Family::IPv6;
std::memcpy(ip.bytes.data(), &reinterpret_cast<const sockaddr_in6*>(address)->sin6_addr, 16);
} else {
return false;
}
ip.prefix_length = prefix_length;
return true;
}
// The row that identifies one address on one interface.
MIB_UNICASTIPADDRESS_ROW make_row(unsigned interface_index, const IpPrefix& ip)
{
MIB_UNICASTIPADDRESS_ROW row;
InitializeUnicastIpAddressEntry(&row); // sets lifetimes, origin and flags to sane defaults
row.InterfaceIndex = interface_index;
row.OnLinkPrefixLength = static_cast<UINT8>(ip.prefix_length);
if (ip.family == Family::IPv4) {
row.Address.si_family = AF_INET;
std::memcpy(&row.Address.Ipv4.sin_addr, ip.bytes.data(), 4);
} else {
row.Address.si_family = AF_INET6;
std::memcpy(&row.Address.Ipv6.sin6_addr, ip.bytes.data(), 16);
}
return row;
}
} // namespace
std::vector<Interface> list_interfaces(int& error)
{
error = 0;
// Microsoft recommends starting with a 15 KB buffer and retrying with the
// size the call reports, because adapters can appear between calls.
ULONG size = 15000;
std::vector<unsigned char> buffer;
ULONG result = ERROR_BUFFER_OVERFLOW;
for (int attempt = 0; attempt < 3 && result == ERROR_BUFFER_OVERFLOW; ++attempt) {
buffer.resize(size);
result = GetAdaptersAddresses(AF_UNSPEC,
GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER,
nullptr, reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buffer.data()), &size);
}
if (result != ERROR_SUCCESS) {
error = static_cast<int>(result);
return {};
}
std::vector<Interface> list;
for (auto* adapter = reinterpret_cast<IP_ADAPTER_ADDRESSES*>(buffer.data()); adapter != nullptr;
adapter = adapter->Next) {
Interface in;
in.name = to_utf8(adapter->FriendlyName);
// IfIndex is 0 when IPv4 is disabled on the adapter; then use the IPv6 index.
in.index = adapter->IfIndex != 0 ? adapter->IfIndex : adapter->Ipv6IfIndex;
in.up = adapter->OperStatus == IfOperStatusUp;
in.loopback = adapter->IfType == IF_TYPE_SOFTWARE_LOOPBACK;
if (adapter->PhysicalAddressLength > 0)
in.mac = mac_to_string(adapter->PhysicalAddress, adapter->PhysicalAddressLength);
for (auto* unicast = adapter->FirstUnicastAddress; unicast != nullptr; unicast = unicast->Next) {
IpPrefix ip;
if (to_ip_prefix(unicast->Address.lpSockaddr, unicast->OnLinkPrefixLength, ip))
in.addresses.push_back(ip);
}
list.push_back(in);
}
std::sort(list.begin(), list.end(), [](const Interface& a, const Interface& b) { return a.index < b.index; });
return list;
}
int add_address(unsigned interface_index, const IpPrefix& address)
{
// The address lasts until the next restart or until the adapter is reset:
// CreateUnicastIpAddressEntry does not write to the persistent store.
MIB_UNICASTIPADDRESS_ROW row = make_row(interface_index, address);
return static_cast<int>(CreateUnicastIpAddressEntry(&row));
}
int remove_address(unsigned interface_index, const IpPrefix& address)
{
MIB_UNICASTIPADDRESS_ROW row = make_row(interface_index, address);
// Deleting an address that is not there fails with ERROR_INVALID_PARAMETER,
// which hides the real cause. Look it up first: GetUnicastIpAddressEntry
// reports a missing address as ERROR_NOT_FOUND.
MIB_UNICASTIPADDRESS_ROW existing = row;
const DWORD lookup = GetUnicastIpAddressEntry(&existing);
if (lookup != NO_ERROR)
return static_cast<int>(lookup);
return static_cast<int>(DeleteUnicastIpAddressEntry(&row));
}
bool is_access_denied(int error) { return error == ERROR_ACCESS_DENIED; }
bool is_already_present(int error) { return error == ERROR_OBJECT_ALREADY_EXISTS; }
bool is_not_found(int error) { return error == ERROR_NOT_FOUND || error == ERROR_FILE_NOT_FOUND; }
bool is_not_supported(int error) { return error == ERROR_NOT_SUPPORTED; }
std::string error_text(int error)
{
const char* what = nullptr;
switch (error) {
case ERROR_ACCESS_DENIED: what = "access denied: run as administrator"; break;
case ERROR_OBJECT_ALREADY_EXISTS: what = "the address is already assigned"; break;
case ERROR_NOT_FOUND:
case ERROR_FILE_NOT_FOUND: what = "the address or interface was not found"; break;
case ERROR_INVALID_PARAMETER: what = "invalid parameter"; break;
case ERROR_NOT_SUPPORTED: what = "not supported: is IPv6 disabled?"; break;
default: break;
}
std::string text = "error " + std::to_string(error);
if (what)
text += std::string(" (") + what + ")";
return text;
}
The listing code follows Microsoft’s guidance on two points that trip people up:
- Buffer size. The list’s size is not known in advance. The recommended pattern starts with a 15 KB buffer and, if the call returns
ERROR_BUFFER_OVERFLOW, retries with the size it reports. The loop allows three attempts, because an adapter can appear between two calls. - Names are wide strings.
FriendlyName(“Ethernet”, “Wi-Fi”) iswchar_t. The code converts it to UTF-8 withWideCharToMultiByte, so the rest of the program works withstd::string.
Windows: Adding and Removing an Address
CreateUnicastIpAddressEntry adds one address, IPv4 or IPv6, described by a MIB_UNICASTIPADDRESS_ROW. DeleteUnicastIpAddressEntry removes it. The steps:
- Call
InitializeUnicastIpAddressEntryon the row. It fills in defaults for the lifetimes, the address origin and the flags; skipping it leaves garbage in fields the call reads. - Set
InterfaceIndex, the address andOnLinkPrefixLength. - Call
CreateUnicastIpAddressEntry(orDeleteUnicastIpAddressEntrywith the same row). - Check the result:
NO_ERROR,ERROR_ACCESS_DENIEDwithout administrator rights,ERROR_OBJECT_ALREADY_EXISTSfor an address that is already there.
Three facts from Microsoft’s documentation shape how you use these calls:
- The address is not persistent. Restarting the computer removes it, and so does resetting the adapter. For a permanent address, Microsoft points to
netshor the WMI methodWin32_NetworkAdapterConfiguration.EnableStatic. - Administrator rights are required. For an administrator account other than the built-in Administrator, that means running the program elevated (“Run as administrator”) or giving it a manifest with
requestedExecutionLevelset torequireAdministrator. - A new address may not be usable at once. Windows runs duplicate address detection first. A program that needs to use the address right away should poll
GetUnicastIpAddressEntryuntil itsDadStateisIpDadStatePreferred, or subscribe withNotifyUnicastIpAddressChange. - Removing a missing address gives a misleading error.
DeleteUnicastIpAddressEntryreturnsERROR_INVALID_PARAMETER(87), notERROR_NOT_FOUND, when the address is not on the interface. The tests found this on Windows 11.remove_addresstherefore looks the address up withGetUnicastIpAddressEntryfirst, which does reportERROR_NOT_FOUND, so the caller gets the same “not found” answer on Windows and Linux.
The IPv4-only AddIPAddress and DeleteIPAddress still exist, but they work through an “NTE context” number instead of the address itself, and cannot handle IPv6. New code should use the unicast entry functions.
Linux: Listing Interfaces with getifaddrs
On Linux, getifaddrs returns one entry per address, not per interface: an interface with an IPv4 address, an IPv6 address and a MAC address appears three times. The code groups the entries by name. The entry’s family says what it holds: AF_INET and AF_INET6 carry an address and its netmask, and AF_PACKET carries the hardware (MAC) address.
// interfaces_linux.cpp - Linux implementation: getifaddrs() to list,
// an rtnetlink socket to add and remove addresses.
#include "interfaces.h"
#include <cerrno>
#include <cstring>
#include <ifaddrs.h>
#include <linux/if_packet.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <net/if.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <unistd.h>
#include <algorithm>
#include <memory>
namespace {
int count_prefix_bits(const unsigned char* mask, std::size_t length)
{
int bits = 0;
for (std::size_t i = 0; i < length; ++i)
for (int b = 7; b >= 0; --b)
bits += (mask[i] >> b) & 1;
return bits;
}
Interface& find_or_add(std::vector<Interface>& list, const ifaddrs* entry)
{
for (Interface& in : list)
if (in.name == entry->ifa_name)
return in;
Interface in;
in.name = entry->ifa_name;
in.index = if_nametoindex(entry->ifa_name);
in.up = (entry->ifa_flags & IFF_UP) != 0;
in.loopback = (entry->ifa_flags & IFF_LOOPBACK) != 0;
list.push_back(in);
return list.back();
}
// Owns a socket file descriptor.
struct Fd {
int fd;
~Fd() { if (fd >= 0) close(fd); }
};
// Sends one RTM_NEWADDR or RTM_DELADDR request and waits for the kernel's answer.
int change_address(int type, int flags, unsigned index, const IpPrefix& ip)
{
Fd sock{socket(AF_NETLINK, SOCK_RAW | SOCK_CLOEXEC, NETLINK_ROUTE)};
if (sock.fd < 0)
return errno;
struct Request {
nlmsghdr header;
ifaddrmsg message;
char attributes[64];
} request{};
request.header.nlmsg_len = NLMSG_LENGTH(sizeof(ifaddrmsg));
request.header.nlmsg_type = static_cast<unsigned short>(type);
request.header.nlmsg_flags = static_cast<unsigned short>(NLM_F_REQUEST | NLM_F_ACK | flags);
request.header.nlmsg_seq = 1;
request.message.ifa_family = ip.family == Family::IPv4 ? AF_INET : AF_INET6;
request.message.ifa_prefixlen = static_cast<unsigned char>(ip.prefix_length);
request.message.ifa_index = index;
// IFA_LOCAL is the interface's own address. For IPv4, IFA_ADDRESS must
// carry the same value (it differs only on point-to-point links).
for (unsigned short attribute : {IFA_LOCAL, IFA_ADDRESS}) {
auto* rta = reinterpret_cast<rtattr*>(reinterpret_cast<char*>(&request) + NLMSG_ALIGN(request.header.nlmsg_len));
rta->rta_type = attribute;
rta->rta_len = static_cast<unsigned short>(RTA_LENGTH(ip.size()));
std::memcpy(RTA_DATA(rta), ip.bytes.data(), ip.size());
request.header.nlmsg_len = NLMSG_ALIGN(request.header.nlmsg_len) + RTA_ALIGN(rta->rta_len);
}
sockaddr_nl kernel{};
kernel.nl_family = AF_NETLINK;
if (sendto(sock.fd, &request, request.header.nlmsg_len, 0,
reinterpret_cast<sockaddr*>(&kernel), sizeof kernel) < 0)
return errno;
// The answer is an NLMSG_ERROR message; error 0 means success.
alignas(nlmsghdr) char reply[4096];
const ssize_t got = recv(sock.fd, reply, sizeof reply, 0);
if (got < 0)
return errno;
const auto* header = reinterpret_cast<const nlmsghdr*>(reply);
if (got < static_cast<ssize_t>(NLMSG_LENGTH(sizeof(nlmsgerr))) || header->nlmsg_type != NLMSG_ERROR)
return EPROTO;
return -static_cast<const nlmsgerr*>(NLMSG_DATA(header))->error;
}
} // namespace
std::vector<Interface> list_interfaces(int& error)
{
error = 0;
ifaddrs* raw = nullptr;
if (getifaddrs(&raw) != 0) {
error = errno;
return {};
}
std::unique_ptr<ifaddrs, decltype(&freeifaddrs)> all(raw, freeifaddrs);
std::vector<Interface> list;
for (const ifaddrs* entry = raw; entry != nullptr; entry = entry->ifa_next) {
Interface& in = find_or_add(list, entry);
if (entry->ifa_addr == nullptr)
continue;
const int family = entry->ifa_addr->sa_family;
if (family == AF_PACKET) {
const auto* link = reinterpret_cast<const sockaddr_ll*>(entry->ifa_addr);
if (link->sll_halen > 0 && !in.loopback)
in.mac = mac_to_string(link->sll_addr, link->sll_halen);
} else if (family == AF_INET || family == AF_INET6) {
IpPrefix ip;
if (family == AF_INET) {
ip.family = Family::IPv4;
std::memcpy(ip.bytes.data(), &reinterpret_cast<const sockaddr_in*>(entry->ifa_addr)->sin_addr, 4);
if (entry->ifa_netmask)
ip.prefix_length = count_prefix_bits(reinterpret_cast<const unsigned char*>(
&reinterpret_cast<const sockaddr_in*>(entry->ifa_netmask)->sin_addr), 4);
} else {
ip.family = Family::IPv6;
std::memcpy(ip.bytes.data(), &reinterpret_cast<const sockaddr_in6*>(entry->ifa_addr)->sin6_addr, 16);
if (entry->ifa_netmask)
ip.prefix_length = count_prefix_bits(reinterpret_cast<const unsigned char*>(
&reinterpret_cast<const sockaddr_in6*>(entry->ifa_netmask)->sin6_addr), 16);
}
in.addresses.push_back(ip);
}
}
std::sort(list.begin(), list.end(), [](const Interface& a, const Interface& b) { return a.index < b.index; });
return list;
}
int add_address(unsigned interface_index, const IpPrefix& address)
{
// NLM_F_EXCL: fail with EEXIST instead of silently replacing an existing address.
return change_address(RTM_NEWADDR, NLM_F_CREATE | NLM_F_EXCL, interface_index, address);
}
int remove_address(unsigned interface_index, const IpPrefix& address)
{
return change_address(RTM_DELADDR, 0, interface_index, address);
}
bool is_access_denied(int error) { return error == EPERM || error == EACCES; }
bool is_already_present(int error) { return error == EEXIST; }
bool is_not_found(int error) { return error == EADDRNOTAVAIL || error == ENODEV; }
bool is_not_supported(int error) { return error == EOPNOTSUPP || error == EAFNOSUPPORT; }
std::string error_text(int error)
{
const char* what = nullptr;
switch (error) {
case EPERM:
case EACCES: what = "permission denied: needs root or CAP_NET_ADMIN"; break;
case EEXIST: what = "the address is already assigned"; break;
case EADDRNOTAVAIL: what = "the address is not assigned to that interface"; break;
case ENODEV: what = "no such interface"; break;
case EINVAL: what = "invalid argument"; break;
case EOPNOTSUPP:
case EAFNOSUPPORT: what = "not supported: is IPv6 disabled?"; break;
default: break;
}
std::string text = "error " + std::to_string(error);
if (what)
text += std::string(" (") + what + ")";
return text;
}
getifaddrs gives a netmask, not a prefix length, so count_prefix_bits counts the one bits. The list must be released with freeifaddrs; the std::unique_ptr with a custom deleter does that on every path.
Linux: Adding and Removing an Address with rtnetlink
Linux has no “add address” system call. Tools such as ip addr add talk to the kernel’s routing subsystem through a netlink socket, and the code above does the same. Where Windows has a function call, Linux has a message:
- Open a socket with
socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE). - Build a message: a
nlmsghdrheader with typeRTM_NEWADDR(orRTM_DELADDR), anifaddrmsgwith the family, prefix length and interface index, then the address itself asIFA_LOCALandIFA_ADDRESSattributes. - Ask for an acknowledgement (
NLM_F_ACK) and read the reply: anNLMSG_ERRORmessage whoseerrorfield is 0 on success or a negativeerrno.
NLM_F_CREATE | NLM_F_EXCL makes adding an existing address fail with EEXIST, which matches Windows’ ERROR_OBJECT_ALREADY_EXISTS. Without NLM_F_EXCL, the kernel would quietly accept the duplicate, and a program could not tell whether it had changed anything. The test checks this, and a deliberate bug that drops the flag is caught.
The rtnetlink manual page lists every message type and attribute.
The ipaddr Command-Line Tool
The tool ties the pieces together. It accepts an interface by index or name, validates the address before touching the system and prints a clear message for each failure:
// ipaddr.cpp - list network interfaces, and add or remove IP addresses.
//
// ipaddr list
// ipaddr add <interface> <address>/<prefix length>
// ipaddr remove <interface> <address>/<prefix length>
//
// <interface> is an interface index or name ("Ethernet", "eth0").
// Adding and removing need administrator rights (Windows) or root (Linux).
#include "interfaces.h"
#include <cstdlib>
#include <iostream>
#include <string>
namespace {
int usage()
{
std::cout << "usage: ipaddr list\n"
" ipaddr add <interface> <address>/<prefix length>\n"
" ipaddr remove <interface> <address>/<prefix length>\n";
return 2;
}
void print(const Interface& in)
{
std::cout << in.index << " " << in.name << " " << (in.up ? "up" : "down");
if (in.loopback)
std::cout << " loopback";
if (!in.mac.empty())
std::cout << " MAC " << in.mac;
std::cout << '\n';
for (const IpPrefix& ip : in.addresses) {
std::cout << " " << prefix_to_string(ip);
if (ip.family == Family::IPv4)
std::cout << " (mask " << ipv4_mask(ip.prefix_length) << ")";
std::cout << '\n';
}
}
// Accepts an index ("12") or a name ("Ethernet"). Returns 0 if there is no match.
unsigned find_interface(const std::vector<Interface>& list, const std::string& wanted)
{
for (const Interface& in : list)
if (in.name == wanted || std::to_string(in.index) == wanted)
return in.index;
return 0;
}
} // namespace
int main(int argc, char** argv)
{
if (argc < 2)
return usage();
const std::string command = argv[1];
int error = 0;
const std::vector<Interface> list = list_interfaces(error);
if (error != 0) {
std::cout << "cannot list interfaces: " << error_text(error) << '\n';
return 1;
}
if (command == "list" && argc == 2) {
for (const Interface& in : list)
print(in);
return 0;
}
if ((command != "add" && command != "remove") || argc != 4)
return usage();
const auto address = parse_prefix(argv[3]);
if (!address) {
std::cout << "\"" << argv[3] << "\" is not a valid address such as 192.168.1.50/24 or fd00::5/64\n";
return 1;
}
const unsigned index = find_interface(list, argv[2]);
if (index == 0) {
std::cout << "no interface named or numbered \"" << argv[2] << "\" (see: ipaddr list)\n";
return 1;
}
error = command == "add" ? add_address(index, *address) : remove_address(index, *address);
if (error != 0) {
std::cout << command << " " << prefix_to_string(*address) << " failed: " << error_text(error) << '\n';
return 1;
}
std::cout << (command == "add" ? "added " : "removed ") << prefix_to_string(*address)
<< (command == "add" ? " to " : " from ") << "interface " << index << '\n';
return 0;
}
A session on Linux, run as root, adding an address to the loopback interface and removing it again:
$ ipaddr add lo 198.18.77.77/32
added 198.18.77.77/32 to interface 1
$ ipaddr add lo 198.18.77.77/32
add 198.18.77.77/32 failed: error 17 (the address is already assigned)
$ ipaddr list
1 lo up loopback
127.0.0.1/8 (mask 255.0.0.0)
198.18.77.77/32 (mask 255.255.255.255)
$ ipaddr remove lo 198.18.77.77/32
removed 198.18.77.77/32 from interface 1
$ ipaddr remove lo 198.18.77.77/32
remove 198.18.77.77/32 failed: error 99 (the address is not assigned to that interface)
The list output is cut after the first interface. On Windows the commands are the same, with Windows interface names (ipaddr add Ethernet 192.168.1.60/24) in an elevated terminal. Without root, the add fails with a message that names the cause:
add 198.18.77.77/32 failed: error 1 (permission denied: needs root or CAP_NET_ADMIN)
Permissions and Safety
Changing addresses is a privileged operation on both systems, and a mistake can cut a machine off the network:
- Ask for exactly the rights you need. On Windows, a tool that changes addresses should declare
requireAdministratorin its manifest so Windows prompts once, instead of failing halfway. On Linux, a service can be grantedCAP_NET_ADMIN(for example withAmbientCapabilities=CAP_NET_ADMINin a systemd unit) instead of running as root. - Validate before you call.
ipaddrparses the address and resolves the interface before making any change, so a typo never reaches the network stack. - Add the new address before removing the old one. Removing the address a remote session is using first will drop that session, including the SSH or Remote Desktop connection you are working through.
- Expect a manager to override you. DHCP clients, NetworkManager and Windows’ own configuration can replace addresses that a program added. For a lasting change, configure it where the system’s network manager reads it.
- Use reserved ranges for tests. The tests here use
198.18.0.0/15(reserved for benchmarking) andfd00::/8(unique local IPv6) on the loopback interface, so they cannot collide with a real network.
Common Mistakes When Changing IP Addresses in Code
- Using
GetAdaptersInfoin new code. It returns IPv4 addresses only. UseGetAdaptersAddresses. - Calling
GetAdaptersAddressesonce with a guessed buffer. HandleERROR_BUFFER_OVERFLOWand retry with the reported size. - Skipping
InitializeUnicastIpAddressEntry. The row has fields you do not set yourself, and they must hold valid defaults. - Reading
ERROR_INVALID_PARAMETERfrom a delete as “bad input”. On Windows it can simply mean the address was already gone. Check withGetUnicastIpAddressEntry. - Storing interface indexes. They can change when an adapter is disabled and enabled. Store the name or the LUID, and look up the index when you need it.
- Expecting the change to survive a restart. Neither API writes the persistent configuration.
- Using
inet_addr. It cannot report an error for255.255.255.255(its error value is that same address), it is IPv4-only and MSVC marks it deprecated. Useinet_ptonor a parser like the one above. - Copying command-line text into fixed-size
chararrays withstrcpy. A long argument overflows the buffer. Usestd::string. - Printing
DWORDvalues with%d. They are unsigned; use%luorstd::cout.
Key Takeaways
- An interface can hold several addresses. “Changing” an address means adding the new one and removing the old one.
- On Windows:
GetAdaptersAddressesto list,CreateUnicastIpAddressEntryandDeleteUnicastIpAddressEntryto change. On Linux:getifaddrsto list,RTM_NEWADDRandRTM_DELADDRon a netlink socket to change. - Both need administrator rights or
CAP_NET_ADMIN, and neither change survives a restart. - Keep address parsing and formatting portable, and test it against
inet_ptonandinet_ntop. - Refer to interfaces by name; indexes can change.
Conclusion
Changing an IP address from C++ takes three operations on each platform: list what is there, add an address, remove one. The APIs differ more in style than in substance, a function call with a row structure on Windows and a message on a socket on Linux, and a thin shared interface hides that difference from the rest of a program. The parts that need the most care are not the calls themselves but what surrounds them: validating input, reporting the exact error, holding the right privileges and remembering that the change lasts only until the next restart.
For the socket APIs that use these addresses, see Windows Sockets (Winsock2) programming in C++ and the TCP client and server in C, and for local communication without IP addresses at all, named pipes in C++. More C++ topics are in the C++ section.
Source Code and Tests
All programs on this page are in the networking/ip-configuration directory of the MYCPLUS C++ examples repository.
Build and test:
cmake -S . -B build
cmake --build build --config Release
ctest --test-dir build -C Release --output-on-failure
What the build checks.
- Compilers: GCC and Clang under C++17 and C++20 with
-Wall -Wextra -pedantic -Werror, and MSVC with/W4 /WX /permissive-. - The parser: fixed answers for IPv4, IPv6, prefixes, masks and MAC addresses, plus agreement with the operating system’s
inet_ptonandinet_ntopon 15 valid and invalid inputs. - The interface list: a loopback interface with
127.0.0.1/8must be found. - A real change:
change_testadds198.18.77.77/32andfd00:6d79:6370:6c75::77/128to the loopback interface, checks that they appear, checks that adding again reports “already assigned”, removes them and checks that removing again reports “not found”. Without administrator rights or root, it reports itself as skipped. - The tool: the messages for a missing command, an invalid address and an unknown interface.
ipaddr listmust show the loopback address. - Sanitizers: on Linux, every test also runs under AddressSanitizer and UndefinedBehaviorSanitizer.
What I Verified
Everything in the Ubuntu column was run for this article on Ubuntu 24.04 (x86-64, GCC 13.3, Clang 18.1, CMake 3.28), as root. The Windows column comes from run_all.ps1 in the repository, run on Windows 11 (build 26300) with MSVC from an administrator prompt.
| Check | Ubuntu 24.04 | Windows 11 |
|---|---|---|
| Build with warnings as errors | GCC and Clang, C++17 and C++20: passed | MSVC /W4 /WX /permissive-, C++17 and C++20: passed |
| CTest: 7 tests | 7 of 7 in all four configurations | 7 of 7 in C++17 and in C++20 |
Adding and removing real addresses (change_test) | IPv4 passed; IPv6 skipped, because IPv6 is disabled in the test system | IPv4 and IPv6 passed in C++17 and C++20 |
| AddressSanitizer and UndefinedBehaviorSanitizer, every test | 7 of 7, clean | Not applicable |
| Valgrind memcheck | No errors, no leaks | Not applicable |
| Deliberate mistakes that a test must catch | All 5 caught | All 6 caught (3 shared with Linux, 3 Windows-only) |
Not covered: macOS and the BSDs, which use ioctl(SIOCAIFADDR) instead of netlink. Gateways, DNS servers and persistent configuration are outside this article.


