How to find slash format of an IP address?

Posted on

QUESTION :

For example,
in this IP address: 145.32.59.24

the slash format should be /16 in the answer.

But I have no clue how this to determine it.

I understand this is a class B IP address.

Please help me.. I have been trying so hard to figure this out.

ANSWER :

Since Classless Internet Domain Routing (CIDR) was introduced in 1993, the ABC “classes” of network/host have become less and less useful and followed. There is no reliable way to determine the partitioning of an IPv4 address into its network and host components from the address alone. The /n format for specifying the netmask assumes a contiguous netmask of that many bits, with the rightmost remainder being the host portion.

So the old class A would be expressed as /8, B as /16, and C as /24. With CIDR, though, you are not limited to those partitions but can split the 32-bit address arbitrarily. You need the netmask to determine the proper /n. Conversely, given the /n, one can determine the netmask. For instance, /16 would have a 255.255.0.0 netmask.

This is called the ‘netmask’; not the ‘slash format’. If anything, you can call it ‘CIDR notation’. The format is generally irrelevant. This will return the netmask in dot-notation format:

#!/bin/sh
ifconfig "$1" | sed -rn '2s/ .*:(.*)$/1/p'

Just call it like: script.sh eth0 . If you want to you can parse this to create the CIDR notation or you can try to parse it from the output of ip addr which displays in CIDR notation already. I don’t have this code handy though.

You may have noticed that neither of these solutions actually take an IP address and spit out a netmask. To do that is not possible. The reason we need to specify a netmask when configuring our IP is because it cannot automatically be determined by the IP. The netmask is a filter to be applied to an IP address. It contains information not inherent to an IP address. Both of these solutions are actually just returning the netmask used to configure the interface.