Skip to content

Beginner · IPv4 addressing · topic 15 of 57 · 25 min

Validating addresses and checking the same subnet

Explanation

A valid IPv4 address has exactly four parts, each a whole number from 0 to 255, with no letters, spaces or leading zeros. Two hosts are in the same subnet when their addresses give the same network after ANDing with the same mask. Many real outages come from small addressing slips: a wrong mask on one PC, a host address typed as a network, or two devices with the same IP.

Why validation matters

Addresses are typed by people into forms, configuration files, firewall rules and scripts. A single typo, 192.168.1.300 or 10.0.0, can break a deployment or open a hole in a firewall. Any tool you write that takes an IP address should check it first and give a clear error.

The rules for a valid IPv4 address

  1. Exactly four parts separated by dots. 10.0.0 and 1.2.3.4.5 are invalid.
  2. Each part is made only of the digits 0 to 9. No letters, no spaces, no plus or minus signs, and no empty parts like 1..2.3.
  3. Each part is between 0 and 255.
  4. No leading zeros: 010.1.1.1 is rejected. Some old tools read a leading 0 as an octal (base 8) number, so 010 meant 8, not 10. Modern Python refuses leading zeros to avoid that confusion.
python
import ipaddress

for text in ["192.168.1.10", "192.168.1.300", "10.0.0", "010.1.1.1"]:
    try:
        print(text, "->", ipaddress.ip_address(text))
    except ValueError as error:
        print(text, "-> invalid:", error)
ip_address raises ValueError for anything that is not a valid address. Catch it and show a friendly message.

Are two hosts in the same subnet?

A PC sends a packet directly to a destination when the destination is in its own subnet, and to the default gateway when it is not. The test is the AND from earlier: AND both addresses with the mask. If the results are equal, they are in the same subnet.

With the block size method you do it in your head. Find the block that each address falls into. Same block, same subnet.

  • 192.168.1.10 and 192.168.1.70 with /26: block size 64. 10 is in 0 to 63 and 70 is in 64 to 127. Different subnets, so they need a router to talk.
  • 10.0.5.20 and 10.0.6.30 with /23: block size 2 in the third octet. 5 is in 4 to 5 and 6 is in 6 to 7. Different subnets.
  • 172.16.20.1 and 172.16.31.254 with /20: block size 16 in the third octet. Both 20 and 31 are in 16 to 31. Same subnet.
python
import ipaddress

net = ipaddress.ip_network("192.168.1.10/26", strict=False)
print(net)                                          # 192.168.1.0/26
print(ipaddress.ip_address("192.168.1.70") in net)  # False
print(ipaddress.ip_address("192.168.1.40") in net)  # True
strict=False lets you pass a host address; Python clears the host bits for you. The in operator tests membership.

With strict=True (the default), ip_network("192.168.1.10/26") raises ValueError, because 192.168.1.10 has host bits set and is not a network address. That is Python telling you that you typed a host where a network was expected.

Common mistakes in real networks

Host address used as a network. Someone writes a route or firewall rule for 10.4.7.25/24 when they meant 10.4.7.0/24. Some devices quietly fix it, others reject it, and others store something unexpected. Always write the real network address.

Wrong mask on one PC. PC A is 192.168.1.10/24 and PC B is 192.168.1.200 but was given /25 by mistake. A thinks B is local and sends to it directly. B works out that A (in 192.168.1.0 to 127) is not in its subnet (192.168.1.128 to 255) and sends replies to the default gateway instead. Traffic may work one way, through the router, or not at all. Symptoms that "half work" are a strong hint to check masks.

Duplicate IP addresses. Two devices have the same address, often a static address typed by hand that is also in the DHCP pool. Both fight over it: connections drop at random, and Windows may show an "IP address conflict" warning. Fix it by keeping static addresses outside the DHCP range and recording every static address in an IP plan.

Careful: Do not validate IP addresses with a quick regular expression like \d+\.\d+\.\d+\.\d+. It accepts 999.999.999.999. Use ipaddress, or check each part as a number as you will do in the task below.
Tip: When two hosts cannot talk, write both addresses and masks next to each other and work out both networks. It takes a minute and catches most beginner mistakes before you start changing cables.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Validating addresses and checking the same subnet · 1/7

Validating addresses

IP addresses are typed by people, so they are often wrong. Let us learn to check them and to test if two hosts share a subnet.

Prefer a video by a teacher? Find free videos on “how to check if two ip addresses are in the same subnet” on YouTube ↗

In real life: A registration form at a college fest

Students at an engineering college build a small web app that lets visiting teams register the IP of the gaming PC they bring to the LAN tournament. The first version stored whatever was typed, and on the day the organisers found entries like "192.168.1", "192,168.1.5" and "192.168.1.256". In the next year's version they validate every address and check it is inside the tournament subnet 10.50.0.0/22 before saving.

python
import ipaddress

LAN = ipaddress.ip_network("10.50.0.0/22")

def accept(text):
    try:
        return ipaddress.ip_address(text) in LAN
    except ValueError:
        return False

print(accept("10.50.3.17"), accept("10.50.4.1"), accept("192.168.1"))
Shows True False False.

Practice (0/4 done)

Task 1 · Code · Python

Write is_valid_ipv4(text) WITHOUT the ipaddress module. Return True only if the text has exactly four parts separated by dots, every part is made only of the characters 0 to 9 (not empty), has no leading zero (except the single digit "0"), and is from 0 to 255.

Task 2 · Code · Python

Write same_subnet(a, b, prefix) that returns True when addresses a and b are in the same subnet for the given prefix length. Use ipaddress.ip_network(..., strict=False) and the in operator.

Task 3 · Code · Javascript

Now in JavaScript. toInt(ip) is written for you: it turns an address into one number. Finish sameSubnet(a, b, prefix). Hint: a subnet with prefix p holds 2 ** (32 - p) addresses, so two addresses are in the same subnet when Math.floor(number / blockSize) is the same for both.

Task 4 · Question

PC A is 192.168.1.10/24 and PC B is 192.168.1.200/25. Both have gateway 192.168.1.1. What happens when A pings B?

Quick quiz

Question 1

1.Which of these is a valid IPv4 address?

Question 2

2.What does ipaddress.ip_network("192.168.1.10/26") do with the default strict=True?

Question 3

3.Are 10.1.1.100/25 and 10.1.1.130/25 in the same subnet?

Question 4

4.Users report that connections drop at random, and Windows shows an "IP address conflict" warning. What is the most likely cause?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

Which of these is a valid IPv4 address?

Answer: 172.16.254.1

172.16.254.1 has four parts, each from 0 to 255.

What does ipaddress.ip_network("192.168.1.10/26") do with the default strict=True?

Answer: Raises ValueError because host bits are set

With strict=True, the address must be a network address. 192.168.1.10 has host bits set, so it raises ValueError. Use strict=False to clear them.

Are 10.1.1.100/25 and 10.1.1.130/25 in the same subnet?

Answer: No

/25 splits the octet at 128. 100 is in 0 to 127, 130 is in 128 to 255, so they are in different subnets.

Users report that connections drop at random, and Windows shows an "IP address conflict" warning. What is the most likely cause?

Answer: Two devices have the same IP address

An IP conflict means two devices use the same address, often a static address that is also in the DHCP pool.

Which address is private?Related

Answer: 172.20.1.5

172.16.0.0/12 covers 172.16.x.x to 172.31.x.x, so 172.20.1.5 is private; 172.32.1.5 is not.

From IP addresses, subnets and CIDR

Where does Cisco IOS expect a wildcard mask instead of a subnet mask?Related

Answer: In access-list statements and the OSPF network command

Interfaces take subnet masks. ACLs and OSPF network statements take wildcard masks.

From Subnet masks, prefix length and wildcard masks

Is 192.168.0.255/23 a usable host address?Related

Answer: Yes, the subnet runs from 192.168.0.0 to 192.168.1.255

In a /23 the broadcast is 192.168.1.255. 192.168.0.255 is in the middle of the range, so it is a normal host.

From Network, broadcast and usable host range

Each subnet must hold 25 hosts. Which prefix wastes the fewest addresses?Related

Answer: /27

/27 gives 30 usable hosts. /28 gives only 14, and /26 wastes more.

From Subnetting a network into equal subnets

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. This is the last topic of “IPv4 addressing”. The module exam comes next.
  2. Module 3 exam: IPv4 addressing · 13 questions · 20 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Subnetting practice and IPv6. 57 topics left in the course before the final exam.

← Previous: Network, broadcast and usable host range