What is the easiest way using common linux tools to check if a bunch of ip addresses belongs to given network?

断了今生、忘了曾经 提交于 2019-12-23 18:19:43

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/435606/what-is-the-easiest-way-using-common-linux-tools-to-check-if-a-bunch-of-ip-addre

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!