Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid hard coding network address for bridge #4

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 66 additions & 2 deletions lib/vagrant-bhyve/driver.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
require "digest/md5"
require "io/console"
require "ruby_expect"

require "json"
require "ipaddr"

module VagrantPlugins
module ProviderBhyve
Expand Down Expand Up @@ -210,7 +211,7 @@ def enable_nat(bridge, ui)
# Choose a subnet for this bridge
index = bridge_name =~ /\d/
bridge_num = bridge_name[index..-1]
sub_net = "172.16." + bridge_num
sub_net = _find_free_net.split('.')[0,2].join(".") + "." + bridge_num

# Config IP for the bridge
execute(false, "#{@sudo} ifconfig #{bridge_name} #{sub_net}.1/24")
Expand Down Expand Up @@ -669,6 +670,69 @@ def grub_bhyve_execute(command, password, member)
end
end

def _find_local_subnets()
netstat4_json = `netstat -rn -4 --libxo json`
my_routes4_json = JSON.parse(netstat4_json)

my_routes4 = my_routes4_json['statistics']['route-information']['route-table']['rt-family'][0]['rt-entry']

local_nets = []
my_routes4.each do |route|
next if route['destination'] == "default"
local_nets.push(route['destination'])
end
return local_nets
end

def _ip_in_subnet(ip, net)
netaddr = IPAddr.new(net)
return netaddr === IPAddr.new(ip)
end

def _find_free_net()
local_networks = _find_local_subnets

# largest to smallest
(0..255).each do |i|
ip = "10." + i.to_s + ".0.0"
found = false
local_networks.each do |net|
if _ip_in_subnet(ip, net)
found = true
end
end
if found == false
return ip.to_s + "/8"
end
end

(16..31).each do |i|
ip = "172." + i.to_s + ".0.0"
found = false
local_networks.each do |net|
if _ip_in_subnet(ip, net)
found = true
end
end
if found == false
return ip.to_s + "/16"
end
end

(0..255).each do |i|
ip = "192.168." + i.to_s + ".0"
found = false
local_networks.each do |net|
if _ip_in_subnet(ip, net)
found = true
end
end
if found == false
return ip.to_s + "/24"
end
end
end # _find_free_net

end
end
end