Update stdlib and concat to 6.1.0 both
[mirror/dsa-puppet.git] / 3rdparty / modules / stdlib / lib / puppet / functions / stdlib / ip_in_range.rb
1 # @summary
2 #   Returns true if the ipaddress is within the given CIDRs
3 #
4 # @example ip_in_range(<IPv4 Address>, <IPv4 CIDR>)
5 #   stdlib::ip_in_range('10.10.10.53', '10.10.10.0/24') => true
6 Puppet::Functions.create_function(:'stdlib::ip_in_range') do
7   # @param ipaddress The IP address to check
8   # @param range One CIDR or an array of CIDRs
9   #   defining the range(s) to check against
10   #
11   # @return [Boolean] True or False
12   dispatch :ip_in_range do
13     param 'String', :ipaddress
14     param 'Variant[String, Array]', :range
15     return_type 'Boolean'
16   end
17
18   require 'ipaddr'
19   def ip_in_range(ipaddress, range)
20     ip = IPAddr.new(ipaddress)
21
22     if range.is_a? Array
23       ranges = range.map { |r| IPAddr.new(r) }
24       ranges.any? { |rng| rng.include?(ip) }
25     elsif range.is_a? String
26       ranges = IPAddr.new(range)
27       ranges.include?(ip)
28     end
29   end
30 end