views:

1141

answers:

5

How do you programmatically find the number of hosts that a netmask supports.

Eg, If you have a /30 , how do you find how many IP's are in it without using a lookup table?

Preferably would be able to work with the "/" notation, rather than 255.xxx.xxx.xxx notation.

A: 

http://www.unixwiz.net/techtips/netmask-ref.html

That will provide you with all of the logic you need to determine what you need to do.

Ian P
Would rather see self-contained comments as other sites may move their information around or even disappear.
paxdiablo
+3  A: 

Here's the formula: 2 ^ (32 - netmask) - 2 where netmask is a bit count as you've shown in the Cisco notation above. So a network with a /30 mask has 2 usable addresses.

The lowest network number always represents the network segment itself and the highest is always the broadcast ... this leads to the -2 at the end of the formula.

For standard notation, convert the aaa.bbb.ccc.ddd netmask into an unsigned 4 byte integer (many networking libraries have this function) and subtract that from 2 ^ 32 - 2.

Steve Moyer
+2  A: 

Where n is the number after the '/'

>>> def number_of_hosts(n):
...     return 2 ** (32 - n)
... 
>>> number_of_hosts(32)
1
>>> number_of_hosts(30)
4
Aaron Maenpaa
I dare say that anytime you use 2 ** x in an integer context, it's probably more idiomatic to write 1 << x, instead. :-P
Chris Jester-Young
remember to subtract 2 for the broadcast andnetwork addresses.
Charles Graham
A: 

2^(32-n) - 2, where n is your number, in this case, 30. The number n, gives you the number of bits that are covered in the address range, which gives you 32-n bits left for your network. Therefore, there are 2^(32-n) possible total addresses. You subtract 2 for the network and broadcast addresses to get your answer.

Charles Graham
A: 

with /30 you have only 4 hosts possible.

32-30 = 2

2^2 = 4

with /24 you have 256 hosts possible 32-24 = 8

8^2 = 256

with /23 you have 512 hosts possible 32-23 = 9

9^2 = 512

its is because of the bit representation of the subnet mask

255.255.255.252 translates into

11111111.11111111.11111111.11111100

note that the 2 last bytes are = 0. this is the same 2 as in 32 - 30 = 2

Also, you lose 2 ip in every subnet, one for the broadcast address and one of the gateway address

Eric
You only lose 2 addresses if you're working in a broadcast medium. /31 is perfectly legal with two valid host addresses on a non-broadcast medium.
Nick Bastin