Method: Jamf::NetworkSegment.network_segment_for_ip

Defined in:
lib/jamf/api/classic/api_objects/network_segment.rb

.network_segment_for_ip(ipaddr, refresh: false, api: nil, cnx: Jamf.cnx) ⇒ Integer?

Which network segment is seen as current for a given IP addr?

According to the Jamf Pro Admin Guide, if an IP is in more than one network segment, it uses the ‘smallest’ (narrowest) one - the one with fewest IP addrs within it.

If multiple ones have the same width, then it uses the one of those with the lowest starting address

Returns:

  • (Integer, nil)

    the id of the current net segment, or nil



274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# File 'lib/jamf/api/classic/api_objects/network_segment.rb', line 274

def self.network_segment_for_ip(ipaddr, refresh: false, api: nil, cnx: Jamf.cnx)
  cnx = api if api

  # get the ip as a 32bit interger
  ip = IPAddr.new(ipaddr.to_s).to_i
  # a hash of NetSeg ids => Range<Integer>
  ranges = network_ranges_as_integers(refresh, cnx: cnx).select { |_id, range| range.include? ip }

  # we got nuttin
  return nil if ranges.empty?

  # if we got only one, its the one
  return ranges.keys.first if ranges.size == 1

  # got more than one, sort by range size/width, asc.
  sorted_by_size = ranges.sort_by { |_i, r| r.size }.to_h

  # the first one is the smallest/narrowest.
  _smallest_range_id, smallest_range = sorted_by_size.first

  smallest_range_size = smallest_range.size

  # select all of them that are the same size
  all_of_small_size = sorted_by_size.select { |_i, r| r.size == smallest_range_size }

  # sort them by the start of each range (r.first)
  # and return the lowest start (returned by min_by)
  my_range_id, _my_range = all_of_small_size.min_by { |_i, r| r.first }

  # and return the id
  my_range_id
end