Skip to content

Instantly share code, notes, and snippets.

@rrdein
Created July 3, 2018 00:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rrdein/7fc0d1bdee60308036c98af00eed7686 to your computer and use it in GitHub Desktop.
Save rrdein/7fc0d1bdee60308036c98af00eed7686 to your computer and use it in GitHub Desktop.
require "ipaddr"
require "nokogiri"
# Open XML file, get servers as an array cidr_list
cidr_list = []
xml_doc = File.open(ARGV[0]) {|f| Nokogiri::XML(f)}
server_lines = xml_doc.xpath("//dict//array//string")
server_lines.each do |line|
data = line.text.split(",")
cidr = data[2]
cidr_list.push cidr
end
# cidr_list contains arrays each representing a CIDR block, defined as follows:
# cidr[0] = the index of the original server line
# cidr[1] = number of times the CIDR is contained (by other than itself)
# cidr[2] = number of other CIDRs that contain this one, besides itself
# sort cidr_list
cidr_list_length = cidr_list.length
# create an array cidrs of size cidr_list_length. Initialize all cidrs[n][1..2] to -1 to
# account for situations like i=1,j=1 where one CIDR is tested against itself.
cidrs = Array.new(cidr_list_length, [nil, -1, -1])
cidr_list_length.times do |i|
cidrs[i][0] = i
cidr_list_length.times do |j|
if(IPAddr.new(cidr_list[j]).include? IPAddr.new(cidr_list[i]))
cidrs[i][1] += 1
cidrs[j][2] += 1
end
puts "#{i} #{j} #{cidrs[0][0]} #{cidrs[0][1]} #{cidrs[0][2]}" # THIS LINE IS FOR TESTING
end
end
/* Portion of Output
0 89 0 0 0
0 90 0 0 0
0 91 0 0 0
0 92 0 1 1
0 93 0 1 1
0 94 0 1 1
0 95 0 2 2
1 0 1 2 2
1 1 1 3 3 <-- Note here how fourth column (cidrs[0][1]) increments even though line 30 should not be able to change it, as #{i} will never be zero again.
1 2 1 3 3
1 3 1 3 3
1 4 1 3 3
1 5 1 3 3
1 6 1 3 3
1 7 1 3 3
1 8 1 3 3
1 9 1 3 3
1 10 1 3 3
1 11 1 3 3
1 12 1 3 3
1 13 1 3 3
1 14 1 3 3
1 15 1 3 3
1 16 1 3 3
*/
@baweaver
Copy link

baweaver commented Jul 3, 2018

require "ipaddr"
require "nokogiri"

# Open XML file, get servers as an array cidr_list
cidr_list = File.read(ARGV[0])
  .yield_self { |f| Nokogiri::XML(f) }
  .xpath("//dict//array//string")
  .map { |node| IPAddr.new(node.text.split(',')[2]) }

references_hash = Hash.new { |h, k| h[k] = Hash.new(0) }

intersections = cidr_list.each_with_object(
  references_hash
) do |cidr_block, cidr_intersections|
  cidr_list.each do |other_cidr|
    next unless other_cidr.include?(cidr_block)

    # Count how many times the given CIDR block is included in other blocks
    cidr_intersections[cidr_block][:inlusions] += 1
    
    # Cound how many times the other CIDR block is depended upon
    cidr_intersections[other_cidr][:dependencies] += 1
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment