Skip to content

Instantly share code, notes, and snippets.

@semistrict
Last active January 26, 2017 15:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save semistrict/5273624 to your computer and use it in GitHub Desktop.
Save semistrict/5273624 to your computer and use it in GitHub Desktop.
Script to run dnsmasq
#!/bin/bash
# These values need to be unique per host-only network
DNSMASQ_IFACE=${1-vboxnet0} # The host-only network interface name (should show up with 'ifconfig -a')
NETWORK_PREFIX=${2-192.168.56} # Network prefix must be unique per host
# You may want to customize the following:
DNSMASQ_DOMAIN=${DNSMASQ_IFACE} # Domain in which names assigned by dnsmasq appear, e.g. myvirtualbox1.vboxnet0
VBOX_HOST_IP="${NETWORK_PREFIX}.1"
VBOX_NETMASK=255.255.255.0
DNSMASQ_LEASE_TIME=10m
DNSMASQ_DHCP_RANGE="${NETWORK_PREFIX}.102,${NETWORK_PREFIX}.200,${DNSMASQ_LEASE_TIME}"
DNSMASQ_LEASEFILE="$TMPDIR/run-dnsmasq-leasefile.${DNSMASQ_DOMAIN}"
DNSMASQ_HOST_NAME="vbox-host.${DNSMASQ_DOMAIN}"
if ! which VBoxManage >/dev/null; then
echo "VBoxManage command not found, is VirtualBox installed?"
exit 1
fi
if ! which dnsmasq >/dev/null; then
echo "dnsmasq command not found, is dnsmasq installed?"
echo "Install with 'brew install dnsmasq'"
exit 1
fi
# Check that the DNSMASQ_IFACE exists
if ! VBoxManage list hostonlyifs | grep -E 'Name:\s+'$DNSMASQ_IFACE > /dev/null; then
echo "Host-only interface not found: $DNSMASQ_IFACE, create with 'VBoxManage hostonlyif create'"
# Note that VirtualBox only supports interfaces with names vboxnet0, vboxnet1, ...
# which it creates sequentially, therefore its difficult to autmatically create the required
# interface in a script, rather bail out here let the user do it manually...
exit 1
fi
# Disable VirtualBox built-in DHCP server
VBoxManage dhcpserver remove --ifname "$DNSMASQ_IFACE" 2>&1 | grep -v 'DHCP server does not exist'
# Configure the host IP address
VBoxManage hostonlyif ipconfig "$DNSMASQ_IFACE" --ip "$VBOX_HOST_IP" --netmask "$VBOX_NETMASK"
echo "nameserver $VBOX_HOST_IP" | sudo tee "/etc/resolver/${DNSMASQ_DOMAIN}" > /dev/null
echo "Running dnsmasq..."
sudo dnsmasq \
--conf-file=/dev/null \
--keep-in-foreground \
--except-interface=lo0 \
--interface="${DNSMASQ_IFACE}" \
--bind-interfaces \
--dhcp-range="${DNSMASQ_DHCP_RANGE}" \
--dhcp-leasefile="${DNSMASQ_LEASEFILE}" \
--local="/${DNSMASQ_DOMAIN}/" \
--expand-hosts \
--domain="${DNSMASQ_DOMAIN}" \
--address="/${DNSMASQ_HOST_NAME}/${VBOX_HOST_IP}" \
--log-queries \
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment