Sub topic 2
The structure of an IPv4 address
This chapter assumes you can already convert one octet between decimal and binary, as covered in the previous chapter on binary and dotted decimal. Here we look at what those four numbers are as a whole: a single 32-bit value, how big the address space is, how software stores and parses addresses, and where the common mistakes come from.
An address is one 32-bit number
An IPv4 address is a 32-bit unsigned integer. Dotted decimal is only a way to write it for humans. Routers and operating systems work with the 32 bits.
The 32 bits are split into four groups of 8 bits. Each group is an octet (a byte). Each octet is written as a decimal number from 0 to 255, and the four numbers are separated by dots.
Two facts follow directly from this layout:
- The largest value of an octet is 11111111 in binary, which is 255. So 256 or higher is never valid in any position.
- The first octet holds the most significant bits. In the integer view, 192.168.1.10 is a much larger number than 10.168.1.192, even though they use the same four values.
Octet weights
Each octet is a digit in a base-256 number. Its weight is a power of 256, which is a power of two.
| Octet position | Bit positions (from the left) | Weight | Value of one unit |
|---|---|---|---|
| 1st | bits 1 to 8 | 256³ = 2²⁴ | 16,777,216 |
| 2nd | bits 9 to 16 | 256² = 2¹⁶ | 65,536 |
| 3rd | bits 17 to 24 | 256¹ = 2⁸ | 256 |
| 4th | bits 25 to 32 | 256⁰ = 2⁰ | 1 |
To get the integer value of an address, multiply each octet by its weight and add the results. For 192.168.1.10:
- 192 × 16,777,216 = 3,221,225,472
- 168 × 65,536 = 11,010,048
- 1 × 256 = 256
- 10 × 1 = 10
The sum is 3,232,235,786. In hexadecimal this is C0A8010A, where each pair of hex digits is one octet (C0 = 192, A8 = 168, 01 = 1, 0A = 10). Hex is often the easiest way to see the octet boundaries in a packet capture.
Size of the address space
With 32 bits there are 2³² = 4,294,967,296 possible values, from 0.0.0.0 (integer 0) to 255.255.255.255 (integer 4,294,967,295).
That is the total count of values, not the count of addresses you can assign to hosts. Later chapters remove large blocks from that total: special-purpose ranges, multicast, reserved space, and the network and broadcast address of every subnet. The structure itself is also why the space ran short. Four billion looked large in the early design, but each network took a whole block of it. The chapters on classful addressing and CIDR cover that history.
Converting in code
Because the address is an integer, conversion is shifting and masking. The shift amounts 24, 16, 8, and 0 correspond to the weights in the table above.
def to_int(address):
parts = address.split(".")
if len(parts) != 4:
raise ValueError("an IPv4 address needs exactly four octets")
value = 0
for part in parts:
if not (part.isascii() and part.isdigit()):
raise ValueError(f"bad octet: {part!r}")
octet = int(part)
if octet > 255:
raise ValueError(f"octet out of range: {octet}")
value = (value << 8) | octet
return value
def to_dotted(value):
if not 0 <= value <= 0xFFFFFFFF:
raise ValueError("value does not fit in 32 bits")
return ".".join(str((value >> shift) & 0xFF) for shift in (24, 16, 8, 0))
number = to_int("192.168.1.10")
print(number) # 3232235786
print(hex(number)) # 0xc0a8010a
print(to_dotted(number)) # 192.168.1.10
print(to_dotted(0xFFFFFFFF)) # 255.255.255.255The loop shifts the running value left by 8 bits to make room, then ORs in the next octet. The reverse direction shifts right to bring each octet into the lowest 8 bits and masks with 0xFF to discard the rest.
In real programs, prefer the standard library over your own parser. The ipaddress module does the same conversion and validates its input.
import ipaddress
address = ipaddress.ip_address("10.0.0.1")
print(int(address)) # 167772161
print(address.packed.hex()) # 0a000001
print(ipaddress.ip_address(167772161)) # 10.0.0.1The packed attribute is the 4-byte form used on the wire.
Byte order on the wire
IPv4 headers carry the address in network byte order, also called big-endian. The most significant octet is sent first, so 192.168.1.10 travels as the bytes C0 A8 01 0A, in the same order you read it left to right.
This matters when you handle addresses as integers in code. A little-endian CPU, such as x86, stores a 32-bit integer with its least significant byte first. If you copy raw bytes from a packet into a native integer without converting, you get 10.1.168.192 as a number, not 192.168.1.10. Use socket.ntohl, struct.unpack("!I", ...), or int.from_bytes(data, "big") to convert. The ! in struct format strings means network order.
What an address identifies
An IPv4 address identifies a network interface, not a computer. A laptop with Wi-Fi and Ethernet has at least two interfaces and usually two addresses. A router has one address per interface. One interface can also carry several addresses. The address also describes a position in the network (which network the interface is attached to), and the next chapter shows how the 32 bits divide into a network part and a host part.
Parsing pitfalls
Most real problems with address structure come from parsers that accept more than the strict four-decimal-octet form. Different tools accept different forms, and that difference causes bugs.
- Too few octets. The classic C function
inet_atonaccepts127.1and reads it as 127.0.0.1: the last number fills all the remaining bits. It also accepts a single large number, so3232235786is a valid address there. Many other parsers reject both. - Leading zeros. Some parsers read
010as octal (decimal 8), so192.168.1.010would be 192.168.1.8. Others read it as decimal 10. Python 3.9.5 and later reject leading zeros inipaddressfor this reason. - Out-of-range octets.
256.1.1.1is invalid. A parser that reads octets into a wider integer and does not check the range can silently produce a wrong value. - Whitespace and signs.
" 1.2.3.4"and"+1.2.3.4"may be accepted by lenient parsers and rejected by strict ones.
import ipaddress
samples = ["192.168.1.10", "256.1.1.1", "192.168.1", "192.168.001.010", "1.2.3.4.5"]
for text in samples:
try:
ipaddress.ip_address(text)
print(f"{text!r}: valid")
except ValueError:
print(f"{text!r}: invalid")Only the first sample is valid on Python 3.9.5 or later.
Edge cases to remember
- 0.0.0.0 and 255.255.255.255 are valid 32-bit values but have special meaning, so they are not assigned to ordinary hosts.
- Each octet is an independent 8-bit field, so any octet can be 0 or 255. An address such as 10.255.0.7 is ordinary. Whether a particular address is usable depends on the network it belongs to, which is a later topic.
- Dotted decimal has no leading-zero padding in the canonical form. Write
192.168.1.10, not192.168.001.010. - Comparing addresses as strings gives the wrong order, because
"9.0.0.1" > "10.0.0.1"is true as text. Compare integers oripaddressobjects.
Exercise
What is the 32-bit integer value of 0.0.1.0, and what is the dotted-decimal form of the integer 65,536?
Show answer
In 0.0.1.0 only the third octet is non-zero, and its weight is 256, so the value is 1 × 256 = 256. The integer 65,536 is 2¹⁶, which is the weight of the second octet, so it is 0.1.0.0.
Exercise
A program reads four bytes from a packet and converts them with a native little-endian integer type. The bytes are C0 A8 01 0A. Which dotted-decimal address does the program print if it splits the integer back into octets from the most significant byte down, and how do you fix it?
Show answer
The little-endian integer is 0x0A01A8C0, which splits into 10.1.168.192 instead of 192.168.1.10. Convert from network byte order first, for example with int.from_bytes(data, "big") or struct.unpack("!I", data).
Exercise
Why is it a bad idea to check whether a user-supplied address is allowed by testing whether the text starts with "10."?
Show answer
Different parsers accept different spellings, such as shortened forms, a single large integer, or octal-looking leading zeros. The text can fail the prefix test and still resolve to a 10.x.x.x host, or the reverse. Parse the text once with a strict parser such as ipaddress.ip_address and check the parsed value.