Skip to content

Compare network addresses in is_subnet_of - #235

Open
amalsaidov wants to merge 1 commit into
achanda:masterfrom
amalsaidov:fix-is-subnet-of-network-address
Open

amalsaidov wants to merge 1 commit into
achanda:masterfrom
amalsaidov:fix-is-subnet-of-network-address

Conversation

@amalsaidov

Copy link
Copy Markdown

Problem

Ipv4Network::is_subnet_of (and the IPv6 equivalent) compares the raw stored addresses of the two networks:

other.ip() <= self.ip() && other.broadcast() >= self.broadcast()

A network can be constructed with host bits set — e.g. "10.1.0.0/15" stores 10.1.0.0 even though its network address is 10.0.0.0. Comparing ip() instead of the masked network address therefore produces wrong results:

let net:  Ipv4Network = "10.1.0.0/16".parse().unwrap();
let net2: Ipv4Network = "10.1.0.0/15".parse().unwrap();
assert!(net.is_supernet_of(net2)); // WRONG: a /16 cannot be a supernet of a /15

It also makes two networks that denote the same range (one with non-zero host bits) fail to be subnets of each other.

This is the bug reported in #152.

Fix

Use network() for both operands, matching the already-correct masking in network(), broadcast() and contains(). Applied to both Ipv4Network and Ipv6Network.

Tests

Added test_is_subnet_of_uses_network_address to the IPv4 and IPv6 test modules (fail before, pass after). Full suite green (cargo test), cargo clippy --all-targets clean.

Fixes #152

is_subnet_of compared the raw stored addresses (ip()) of the two
networks instead of their masked network addresses. Because a network
can be constructed with host bits set (e.g. "10.1.0.0/15" stores
10.1.0.0 even though its network address is 10.0.0.0), the raw-address
comparison let a smaller network be reported as a supernet of a larger
one that happened to share the stored address, and made two networks
denoting the same range fail to be subnets of each other.

Use network() for both operands so the comparison reflects the actual
address ranges, matching the already-correct broadcast()/network()/
contains() behaviour. Fixes the same bug for IPv6.

Fixes achanda#152
Comment thread src/ipv4.rs
fn test_is_subnet_of_uses_network_address() {
let smaller: Ipv4Network = "10.1.0.0/16".parse().unwrap();
let larger: Ipv4Network = "10.1.0.0/15".parse().unwrap();
// 10.1.0.0/15 has network address 10.0.0.0, so the /16 is not inside it,

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems wrong? the /15 does contain the /16

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

is_supernet_of does not work properly

2 participants