Dotted-quad notation

Read an IPv4 address

Lesson 1 of 20 · 8 min · Module 1: Addresses are numbers

An IPv4 address such as 192.168.1.10 is four numbers called octets, separated by dots. Each octet is one byte, so it must be between 0 and 255.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Describe the structure of an IPv4 address
  • Validate text step by step
  • Return early when a rule fails

The idea

Split the text on dots with text.split("."). A valid address has exactly four parts, each made only of digits (part.isdigit()), each between 0 and 255, and without leading zeros such as 01, which some systems read in a different number base.

parts = "192.168.1.10".split(".")
print(parts, len(parts))

01Four bytes, written as text

A computer stores an IPv4 address as 32 bits. People write it as four decimal numbers, one per byte, so 192.168.1.10 is the bytes 192, 168, 1, and 10.

02Check structure before values

First check that there are exactly four parts. Only then is it safe to look at each part. Calling int() on "a" would raise an error, so check isdigit() before converting.

print("1.2.3".split("."))
Output
['1', '2', '3']

03Why leading zeros are rejected

Some old software reads 010 as an octal (base 8) number, which is 8, not 10. Rejecting leading zeros removes that ambiguity, which is what the Python ipaddress module does too.

Your turn

Write is_valid_ipv4(text) that returns True for a valid dotted-quad IPv4 address and False otherwise. Reject wrong part counts, non-digits, values above 255, and leading zeros (but 0 itself is fine).

What the checks look for

  • Accepts 192.168.1.10, 0.0.0.0 and 255.255.255.255
  • Rejects 256.1.1.1 and wrong part counts
  • Rejects letters, empty parts, signs and leading zeros
Try it in the editor →

Take this with you

Validate shape first, then each value, and stop at the first problem.

Go a little further

Make the function also return False for input that is not a string, such as None or 42.

Learn Networking Foundations for free

20 short lessons with real code and instant checks.

See the whole course →