What is the easiest way using common linux tools t

2019-07-04 01:33发布

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..

2条回答
走好不送
2楼-- · 2019-07-04 01:53

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
查看更多
3楼-- · 2019-07-04 02:02

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
查看更多
登录 后发表回答