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 { |iface| =~ %r{vboxnet\d+} }

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

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

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

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!