Getting the last inactive vboxnet interface with Ruby

January 30, 2021 – Samuli Seppänen

This could possibly be the most esoteric blog post I've ever written, but here it goes. So, for reasons even we have difficulty comprehending (hint: related to PXE booting in a Vagrant/Virtualbox environment) we had to find out which inactive vboxnet (hostonly) interface had the highest index. We wanted the code to (hopefully) run on all platforms (Linux, MacOS, Windows) so we wanted to write this code in Ruby. So, this was the brutal but working end-result:

#!/usr/bin/env ruby
#
# Get the highest vboxnet interface that is inactive (down)
#
 
require 'socket'

def vboxnet_ips
  Socket.getifaddrs.select { |iface| iface.name =~ %r{vboxnet\d+} }
end

def inactive_ips(ips)
  ips.select { |iface| iface.flags & Socket::IFF_UP == 0 }
end

def iface_names(ips)
  ifaces = []
  ips.each { |ip| ifaces.append(ip.name) }
  ifaces.uniq
end

def last_inactive_iface(ifaces)
  last_index = ifaces.map { |iface| iface.sub('vboxnet', '').to_i }.sort[-1]
  "vboxnet#{last_index}"
end

p last_inactive_iface(iface_names(inactive_ips(vboxnet_ips)))

This uses the Ruby Socket library. Basically what it does is get all the IPs (not interfaces, filtering out those which are not names vboxnet*. Then it checks which of those are inactive (flag IFF_UP not set). Then it goes through the list of the objects and just gets their name (e.g. "vboxnet0") and removes duplicates. Finally the resulting unordered array of strings is converted into a list of integers, sorted and the highest index along with string "vboxnet" is given back.

This could probably be prettier, but perfect is the worst enemy of "good enough".

Want to talk to an expert?

If you want to reach us, just send us a message or book a free call!
menucross-circle