read_new_name_1
read_new_name_1

Reputation: 23

Calculate the mask for a range of addresses

I have the first and last subnet addres (for example 3.0.0.0 and 3.1.255.255). What algorithm will allow me to calculate the length of the mask of this subnet? Example:

3.0.0.0-3.1.255.255  

By what algorithm can you simply calculate the length of the mask for this range of addresses?

Upvotes: 1

Views: 1390

Answers (1)

Zac67
Zac67

Reputation: 2910

The longest subnet mask is the longest sequence of prefix bits all addresses share. So:

  1. convert first and last IP addresses to integers
  2. count identical bits, starting from HSB - that's the mask length

IPv4 addresses are really 32-bit unsigned integers - the dot notation is just for us humans.

Step 2 can be done by exclusive-oring both addresses which results in all identical bits being 0. Then right shift until the result is zero. The mask length is 32-(number of shifts).

In your example:

3.0.0.0     = 00000011 00000000 00000000 00000000
3.1.255.255 = 00000011 00000001 11111111 11111111
XOR         = 00000000 00000001 11111111 11111111
turns 0 after 17 right shifts => length is 15

Upvotes: 1

Related Questions