views:

223

answers:

3

What is the easiest way using common linux tools to check if a bunch of ip addresses belongs to given network? I just need a number of how many of given addresses belongs to given subnet. Lets say network is 192.16.55.40/27 and addresses is 192.16.55.45, 192.16.55.115, 88.87.45.8, 192.16.55.37, 192.16.55.60 and 192.16.55.210..

+6  A: 

I'm not sure whether you consider Ruby as a "common linux tool" but it has a nice module called IPAddr that has a method called include? for that.

require 'ipaddr'

net1 = IPAddr.new("192.168.2.0/24")
net2 = IPAddr.new("192.168.2.100")
net3 = IPAddr.new("192.168.3.0")
p net1.include?(net2)     #=> true
p net1.include?(net3)     #=> false
Keltia
A: 

I needed this to, and decided to create a short script. I requires sed and bash. I'd call them both common linux tools.

Edit: Script too long to paste, apparently. You can find it here: http://folk.ntnu.no/olechrt/netaddr

$ cat ips

192.16.55.45
192.16.55.115
88.87.45.8
192.16.55.210.11
192.16.55.37
192.16.55.60
192.16.55.210
256.87.45.8

$ cat ips | netaddr 192.16.55.40/27

192.16.55.45
Warning: Input IP "192.16.55.210.11" is invalid.
192.16.55.37
192.16.55.60
Warning: Input IP "256.87.45.8" is invalid.

And finally, for the count you requested: $ cat ips | netaddr 192.16.55.40/27 | wc -l

Warning: Input IP "192.16.55.210.11" is invalid.
Warning: Input IP "256.87.45.8" is invalid.
3
Pianosaurus
A: 

Thanks for scrip, i was looking exacly for thing

misiek