Embedded HandbookApps
All sections › X. Design, networks and IoT
STM32F407, STM32F103 · level intermediate · 16 min read
Open in the interactive handbook

86а. IP addressing in practice: mask, prefix, subnets, VLSM, private addresses and IPv6 in brief

Section 86 introduced the IPv4 address, the mask and the prefix in a single table (86.3) and explained DHCP (86.4) and NAT (86.5). Section 105.5 showed how the stack decides "directly or through the gateway". This section does the same arithmetic by hand and to the end: how to get the network, the broadcast address and the host range from 192.168.1.130/26, how to split a workshop network between devices, cameras and the office, which addresses are special and what 169.254.x.x on a device means. At the end — how lwIP checks it and C code that parses an "a.b.c.d/n" string in firmware.

Binary and hexadecimal notation is in section 0е, byte order in headers is in 106б.2, the lwIP stack itself is in 106в.

Sources: the lwIP source from the Keil pack (lwIP/2.3.0: ip4_addr.h, ip4_addr.c, ip4.c, etharp.c, autoip.c, netif.c); the ipaddress module from the Python standard library as the reference. The section's code ip86a.c is built with gcc 12.2.0 on the PC and run on 35 examples from the text and 55 069 random strings — not a single mismatch with ipaddress; the same file is built with arm-none-eabi-gcc for Cortex-M0, M3 and M4 without warnings.

Terms used in the documentation

Term Meaning
dotted-decimal notation four numbers from 0 to 255
netmask, prefix length which bits are the network; their count
CIDR notation (a.b.c.d/n) an address written with its prefix
network address, broadcast address all-zero and all-one host part
host part, network part the two fields of an address
subnetting, VLSM (variable length subnet mask) splitting into subnets, subnets of different sizes
private address space (RFC 1918) addresses of internal networks
link-local, AutoIP (RFC 3927) a self-assigned address valid on one link
shared address space, CGNAT operator addresses behind the operator's NAT
SLAAC IPv6 address autoconfiguration without a server

86а.1 An address is one 32-bit number

Four numbers with dots are only notation for people. The stack stores the address as one 32-bit number, and each of the four numbers is one byte:

Notation 192.168.1.130
binary 11000000.10101000.00000001.10000010
hexadecimal 0xC0A80182
decimal as a whole 3 232 235 906

Byte by byte: 192 = 0xC0, 168 = 0xA8, 1 = 0x01, 130 = 0x82 — each pair of hex digits is exactly one byte (section 0е.4). The whole number is 0xC0A80182; in a network packet its bytes go most significant first, while in Cortex-M memory they go least significant first, hence htonl (106б.2).

The mask is also a 32-bit number: ones on the left, zeros on the right. Ones mark the network field, zeros the host field. The prefix length is simply the number of ones: /24 is 24 ones, 255.255.255.0; /26 is 26 ones, 11111111.11111111.11111111.11000000, 255.255.255.192, 0xFFFFFFC0.

Prefix Mask Hosts
/8 255.0.0.0 16 777 214
/12 255.240.0.0 1 048 574
/16 255.255.0.0 65 534
/20 255.255.240.0 4 094
/24 255.255.255.0 254
/25 255.255.255.128 126
/26 255.255.255.192 62
/27 255.255.255.224 30
/28 255.255.255.240 14
/29 255.255.255.248 6
/30 255.255.255.252 2

Why the ones are contiguous. The mask answers "where does the network end", and there is only one boundary. 255.255.255.208 is 11111111.11111111.11111111.11010000: after the first zero there is a one again, so this is not a mask. lwIP checks it with ip4_addr_netmask_valid: it finds the first zero and makes sure no ones follow. A shorter way: the inverse of a valid mask looks like 0…01…1, and such a number plus one shares no bits with itself:

/* Маска годна, если её инверсия имеет вид 0…01…1 */
int ip_mask_valid(uint32_t mask)
{
    uint32_t inv = ~mask;
    return (inv & (inv + 1u)) == 0;
}

/* 255.255.255.192 -> 26; негодная маска -> -1 */
int ip_mask_to_prefix(uint32_t mask)
{
    int n = 0;
    if (!ip_mask_valid(mask))
        return -1;
    while (mask) {
        mask <<= 1;
        n++;
    }
    return n;
}

86а.2 Network, broadcast address and hosts

Everything else follows from the address and the mask with three operations:

Address 192.168.1.130 with prefix 26 bit by bit: a mask of 26 ones, network address 192.168.1.128 with zeros in the host field and broadcast 192.168.1.191 with ones in the host field

Two special cases. /32 is one address with no neighbours: this is how a single host is written in access rules and routes. /31 is two addresses on a point-to-point link between two routers: there are only two neighbours and no broadcast is needed, so both addresses go to hosts (RFC 3021). For 10.20.30.40/31 the hosts are 10.20.30.40 and 10.20.30.41, while /30 on the same link would leave only .41 and .42 out of four.

In device code all of this is one function with no division and no loops:

void ip_info(uint32_t ip, unsigned prefix, ip_info_t *r)
{
    r->ip = ip;
    r->prefix = prefix;
    r->mask = ip_mask(prefix);
    r->net = ip & r->mask;                    /* И с маской */
    r->bcast = ip | ~r->mask;                 /* ИЛИ с инверсией маски */
    if (prefix >= 31) {                       /* /31 — два узла (RFC 3021), /32 — один */
        r->first = r->net;
        r->last = r->bcast;
        r->hosts = prefix == 31 ? 2u : 1u;
    } else {
        r->first = r->net + 1u;
        r->last = r->bcast - 1u;
        r->hosts = ~r->mask - 1u;             /* 2^(32-n) - 2 */
    }
}

~mask is 2^(32 − n) − 1, so ~mask - 1 is exactly the host count, and even for /0 it fits in 32 bits. ip_mask is the same as in 105.5: prefix 0 is handled separately because a shift by 32 is undefined in C.


86а.3 Six problems step by step

The answers below are the output of the ip86a program (this section's functions), each compared with ipaddress.

1. 192.168.1.130/26. Prefix 26 = 24 + 2: the first three bytes are entirely network, in the fourth the two top bits belong to the network. 130 = 10000010, under the mask 11000000 it leaves 10000000 = 128. Network 192.168.1.128, broadcast 128 + 63 = 191, hosts from 192.168.1.129 to 192.168.1.190, 62 of them.

2. 172.16.5.200/20. 20 = 16 + 4: two bytes of network in full, in the third the four top bits. 5 = 00000101, under the mask 11110000 it is zero. Network 172.16.0.0, mask 255.255.240.0; the host field has 12 bits, broadcast 172.16.15.255. Hosts from 172.16.0.1 to 172.16.15.254 — 4 094 of them. The address 172.16.5.200 looks "far" from 172.16.0.1, but it is the same subnet.

3. 10.0.0.0/8 into 16 subnets. 16 = 2^4, so we take 4 bits from the host field: prefix 8 + 4 = 12, mask 255.240.0.0. The subnet step is 2^(32 − 12) = 1 048 576 addresses, which is a step of 16 in the second byte: 10.0.0.0/12, 10.16.0.0/12, 10.32.0.0/12 … 10.240.0.0/12. The first has broadcast 10.15.255.255, the last 10.255.255.255, like the whole /8. Each has 1 048 574 hosts.

4. What prefix does a mask have? 255.255.255.224: the last byte is 11100000 — three ones, 24 + 3 = /27, 30 hosts. 255.255.240.0 is /20. 255.255.255.208 and 255.0.255.0 are not masks: ip_mask_to_prefix returns −1.

5. Are 192.168.1.100/25 and 192.168.1.200 in one subnet? /25 splits the last byte in half: 0…127 and 128…255. The device's network is 192.168.1.0, broadcast 192.168.1.127. 200 > 127 — the destination is in another subnet and the packet goes through the gateway; 192.168.1.20 goes directly.

6. A link between two routers. 10.20.30.40/30: network .40, broadcast .43, hosts .41 and .42. The same link as /31 has hosts .40 and .41 (see 86а.2), as /32 a single address 10.20.30.41 and nothing else.


86а.4 Subnets of different sizes: a plan for a workshop

The workshop got 192.168.10.0/24 and has five groups: 100 devices, 40 cameras, 25 office computers, 10 service devices (printers, access points, a server) and a link of two routers. It is worth separating them: in different subnets the cameras' broadcast noise does not reach the devices, and "who may go where" rules (86.6) are written per subnet.

Without VLSM all subnets have the same size, and the largest group dictates it: 100 hosts need a /25, and only two /25 fit in a /24. Five groups will not fit.

With VLSM each group gets its own mask. The rule: groups in descending order, each gets the smallest block 2^k with 2^k − 2 ≥ the required count, and the block starts at an address that is a multiple of its size:

Group Needed Subnet Mask Hosts Broadcast Count
devices 100 192.168.10.0/25 255.255.255.128 .1 – .126 .127 126
cameras 40 192.168.10.128/26 255.255.255.192 .129 – .190 .191 62
office 25 192.168.10.192/27 255.255.255.224 .193 – .222 .223 30
service 10 192.168.10.224/28 255.255.255.240 .225 – .238 .239 14
routers 2 192.168.10.240/30 255.255.255.252 .241 – .242 .243 2

244 addresses of 256 are used; 192.168.10.244/30 and 192.168.10.248/29 are free — 12 addresses in reserve. The subnets do not overlap and each lies entirely inside the /24 — checked with ipaddress. By custom the gateway of each subnet takes the first address (.1, .129, .193, .225), and devices get the rest.

The "largest first" order is not a whim: a /25 block can start only at .0 or .128. If the small subnets are handed out from the start of the range first, the large one no longer lands on a multiple-of-size boundary and space is lost.


86а.5 Special addresses and IPv6 in brief

Range Addresses What it is Where you meet it
10.0.0.0/8 16 777 216 private (RFC 1918) large plant networks, VPN, mobile operators
172.16.0.0/12 1 048 576 private (RFC 1918) offices, internal server networks
192.168.0.0/16 65 536 private (RFC 1918) home and workshop routers
169.254.0.0/16 65 536 link-local the device got no address from DHCP
127.0.0.0/8 16 777 216 loopback, to itself debugging on a PC; never leaves the host
100.64.0.0/10 4 194 304 operator addresses behind its NAT mobile modem, cheap plan

172.16.0.0/12 is not 172.16.x.x. Prefix 12 covers the second byte from 16 to 31: 172.31.255.255 is still private, 172.32.0.1 is not.

169.254.x.x: DHCP did not answer. With no server, a host may pick an address itself in the link-local range (RFC 3927). In lwIP this is the AutoIP module: candidates run from 169.254.1.0 to 169.254.254.255, 65 024 addresses; the first candidate is derived from the last two MAC bytes (LWIP_AUTOIP_CREATE_SEED_ADDR), for MAC 02:12:34:56:78:9A it is 169.254.155.120; before taking it the address is checked for being in use (the ACD module, RFC 5227). Computers do the same. So a device with 169.254.x.x on the network almost always means "DHCP did not get through": no cable to the router, wrong VLAN, the DHCP server is off. With such an address link neighbours are visible but the gateway is not: lwIP sends packets with a link-local address only directly, never through a router (etharp_output).

127.0.0.0/8 is loopback. A packet to 127.0.0.1 does not leave the host. On a PC this is how you test a server running on the same computer. This address has no place in a device's settings.

100.64.0.0/10 — addresses behind the operator's NAT. If a mobile modem got an address from this range, there is an operator NAT between it and the internet, and no port forwarding on your own router will make the device visible from outside (86.5). The device connects to the server itself.

Recognising the address class is a few comparisons of the top bits:

const char *ip_kind(uint32_t ip)
{
    if ((ip >> 24) == 10u)            return "private";     /* 10.0.0.0/8 */
    if ((ip >> 20) == 0xAC1u)         return "private";     /* 172.16.0.0/12 */
    if ((ip >> 16) == 0xC0A8u)        return "private";     /* 192.168.0.0/16 */
    if ((ip >> 16) == 0xA9FEu)        return "link-local";  /* 169.254.0.0/16 */
    if ((ip >> 24) == 127u)           return "loopback";    /* 127.0.0.0/8 */
    if ((ip >> 22) == (100u << 2 | 1u)) return "cgnat";   /* 100.64.0.0/10 */
    return "other";
}

0xAC1 is 172 (0xAC) and the top nibble of the second byte equal to 1 (16…31); 100u << 2 | 1u is 100 and the two top bits of the second byte, 01 (64…127). Checked at the edges of every range: 100.127.255.255 is still the operator, 100.128.0.1 is not.

IPv6 in brief

An address is 128 bits, eight groups of 16 bits in hexadecimal. Leading zeros in a group are dropped, and one longest run of zero groups is replaced by ::: 2001:0db8:0000:0000:0000:0000:0000:0001 is 2001:db8::1, 2001:db8:0:1:0:0:0:1 is 2001:db8:0:1::1. Only one double colon is allowed: otherwise it is unclear how many zeros go where.

A network in IPv6 is almost always /64: 64 bits of network, 64 bits of host — 18 446 744 073 709 551 616 addresses in one subnet. Splitting it further is not done: autoconfiguration relies on this length — lwIP silently skips a prefix of any other length announced by the router (nd6.c).

Every interface has a link-local address from fe80::/10 — it appears by itself, without a server, and works only within the segment. lwIP builds it from the MAC (netif_create_ip6_linklocal_address): it inserts ff:fe in the middle and flips bit 0x02 of the first byte. MAC 02:12:34:56:78:9A gives fe80::12:34ff:fe56:789a.

SLAAC is an address without DHCP: the router announces the /64 network prefix, the host appends its own 64 bits and checks the address is not in use. In lwIP this is the LWIP_IPV6_AUTOCONFIG option (RFC 4862). There is usually no NAT in IPv6, but that does not make the device reachable from outside: incoming connections are cut by the router's firewall, and the "device calls out itself" rule stays.


86а.6 Is the destination in my subnet: lwIP and device code

For every outgoing packet the stack decides one thing: is the destination in my subnet or not. In lwIP this is a macro from ip4_addr.h:

#define ip4_addr_net_eq(addr1, addr2, mask) (((addr1)->addr & \
                                              (mask)->addr) == \
                                             ((addr2)->addr & \
                                              (mask)->addr))

The old name is ip4_addr_netcmp; in this version it is kept as a deprecated synonym. The macro is used in two places. ip4_route walks the network interfaces and picks the one whose subnet contains the destination. etharp_output decides whose MAC to ask for: if the destination is outside the subnet and not in 169.254.0.0/16, the frame goes to the gateway's MAC; with no gateway the packet is not sent at all (ERR_RTE). The address in struct ip4_addr is stored in network byte order, but for AND and comparison the order does not matter: both sides are in the same order.

On a device the address often arrives as a string — from a settings file, a web page or a UART command. Parsing without sscanf and without the library:

/* Разбор "a.b.c.d": вернёт указатель за адресом или 0 при ошибке */
const char *ip_scan(const char *s, uint32_t *out)
{
    uint32_t ip = 0;
    for (int part = 0; part < 4; part++) {
        unsigned v = 0, digits = 0;
        if (s[0] == '0' && s[1] >= '0' && s[1] <= '9')
            return 0;                         /* "01" — ведущий ноль запрещён */
        while (*s >= '0' && *s <= '9') {
            v = v * 10u + (unsigned)(*s++ - '0');
            if (++digits > 3 || v > 255u)
                return 0;
        }
        if (digits == 0)
            return 0;
        ip = ip << 8 | v;
        if (part < 3 && *s++ != '.')
            return 0;
    }
    *out = ip;
    return s;
}

/* Разбор "a.b.c.d/n"; без "/n" — префикс 32. 1 — успех, 0 — ошибка */
int ip_cidr_parse(const char *s, uint32_t *ip, unsigned *prefix)
{
    unsigned n = 32;
    s = ip_scan(s, ip);
    if (s == 0)
        return 0;
    if (*s == '/') {
        unsigned digits = 0;
        n = 0;
        for (s++; *s >= '0' && *s <= '9'; s++, digits++)
            n = n * 10u + (unsigned)(*s - '0');
        if (digits == 0 || digits > 2 || n > 32u)
            return 0;
    }
    *prefix = n;
    return *s == '\0';
}

Leading zeros are forbidden for a reason: the classic inet_aton from the C library reads "010" as octal 8 — it turns the string 010.0.0.1 into 8.0.0.1, so the same text gives different addresses. The ipaddress module rejects such strings too. The strings 192.168.1.256/24, 192.168.01.1/24, 1.2.3.4/33 and 1.2.3/24 are rejected by the function; in the random comparison 10 deliberately broken strings were rejected and not a single valid one.

The check itself is one line, as in lwIP:

/* То же, что ip4_addr_net_eq в lwIP: совпадают ли адреса под маской */
int ip_same_net(uint32_t a, uint32_t b, uint32_t mask)
{
    return (a & mask) == (b & mask);
}

Of 20 000 random pairs 8 754 turned out to be in one subnet — the ip86a answers matched ipaddress in all of them. The whole ip86a.c takes 524 bytes of code for Cortex-M3 and M4, 540 for M0 (arm-none-eabi-gcc 12.2.1, -Os).


86а.7 Pitfalls

Mask 255.255.0.0 on a /24 network: neighbours are there, the server in the next network is not. Device 192.168.1.50/16, server 192.168.2.10 behind a router. With mask /16 the device considers the server a neighbour and asks for its MAC by ARP directly — no answer, the gateway is not even involved. With the correct /24 the same address goes through the gateway.

Mask narrower than needed: some neighbours are "behind the gateway". Device 192.168.1.130/26 on a network that is actually /24: it looks for neighbour 192.168.1.20 through the gateway, and the gateway 192.168.1.1 itself ends up outside its subnet. Whether this works is up to the stack and the router; the right answer is one mask for the whole subnet.

Mask 255.255.255.208. There is no such mask: a one follows a zero. lwIP rejects it with ip4_addr_netmask_valid; in a device's own web interface it is better to enter the mask as a prefix, not as four numbers.

Two devices with one address. Neighbours remember first one MAC, then the other, and the link to both drops intermittently. Causes — an address written by hand into a batch of identical firmware, or one that collided with an address handed out by DHCP. Protection — addresses only from DHCP (with a reservation by MAC, 86.4) or a check that the address is free before taking it (ACD in lwIP).

The device has 169.254.x.x. DHCP did not answer, the address was assigned by the device itself; it will not reach the gateway or the internet. Look for why DHCP did not get through.

Modem with a 100.64.x.x address, port forwarding does not work. The modem is behind the operator's NAT (86.5); the device must connect by itself.

"172.16.0.0/12 is 172.16.x.x". No: from 172.16 to 172.31. The address 172.20.1.1 is private too.

VLSM subnets cut from small to large. The large subnet does not land on a multiple-of-size boundary, addresses are lost. Cut from large to small.

"010" in an address. Some programs read it as 10, inet_aton as octal 8. In firmware it is better to forbid leading zeros.


86а.8 Summary

Next: section 86б "The OSI model and the TCP/IP stack: what works at which layer in a device" — the seven OSI layers and the four TCP/IP layers on the example of a device: what the PHY, the MAC on the chip, the driver, lwIP and the application each do, one MQTT publish byte by byte from the topic to the FCS, and troubleshooting from the bottom up.

Open in the interactive handbook