How exactly does Linux use the prefix length assigned to network interface?

I assigned IP address 192.168.0.1/24 to eth0 in two ways.

A. Adding 192.168.0.1/24 as usual

# ip addr add 192.168.0.1/24 dev eth0
# ping -c 1 192.168.0.2
PING 192.168.0.2 (192.168.0.2) 56(84) bytes of data.
64 bytes from 192.168.0.2: icmp_seq=1 ttl=64 time=0.051 ms

--- 192.168.0.2 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.051/0.051/0.051/0.000 ms
#

B: Adding 192.168.0.1/32 and adding a /24 route

# ip addr add 192.168.0.1/32 dev eth0
                                        # 192.168.0.2 should not be reachable.
# ping -c 1 192.168.0.2
ping: connect: Network is unreachable
                                        # But after adding a route, it is.
# ip route add 192.168.0.0/24 dev eth0
# ping -c 1 192.168.0.2
PING 192.168.0.2 (192.168.0.2) 56(84) bytes of data.
64 bytes from 192.168.0.2: icmp_seq=1 ttl=64 time=0.053 ms

--- 192.168.0.2 ping statistics ---
1 packets transmitted, 1 received, 0% packet loss, time 0ms
rtt min/avg/max/mdev = 0.053/0.053/0.053/0.000 ms
#

Does this mean that adding an IP address with a prefix
is just a shorthand for adding the IP address with /32 prefix
and adding a route afterwards? 
That is, does the prefix length have no meaning
and the real work is done by the route entries?

Or is there any functional difference between the two methods?


Here is another case:
the two nodes can reach each other via direct connection
(no router in between), but don’t share a subnet.

Node 1:

# ip addr add 192.168.0.1/24 dev eth0
# ip route add 192.168.1.0/24 dev eth0
                                        # Finish the config on Node 2
# nc 192.168.1.1 8080 <<< "Message from 192.168.0.1"
Response from 192.168.1.1

Node 2:

# ip addr add 192.168.1.1/24 dev eth0
# ip route add 192.168.0.0/24 dev eth0
                                        # Finish the config on Node 1
# nc -l 0.0.0.0 8080 <<< "Response from 192.168.1.1"
Message from 192.168.0.1
Asked By: Akash Rawal

||

That is, does the prefix length have no meaning and the real work is done by the route entries?

The subnet mask defines your subnet, and thus also defines what the broadcast address is, and to which broadcast IP packets and which ARP requests your machine replies to. So, there’s a difference between you getting a /32 address and setting up your routing tables, and you getting a /24 address.

Note that this isn’t specific to Linux at all; that’s just how IPv4 works.

Answered By: Marcus Müller
Categories: Answers Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.