You can access ports on the host machine through the default gateway inside the guest OS. (Which typically has an IP of 10.0.2.2
.)
For example, if you have a webserver running on port 8000 on your host machine...
echo 'Hello, guest!' > hello
python -m SimpleHTTPServer 8000
You can access it from inside the Vagrant VM at 10.0.2.2:8000
(provided 10.0.2.2
is the ip of the guest's default gateway):
vagrant ssh
curl http://10.0.2.2:8000/hello # Outputs: Hello, guest!
To find the IP of the default gateway inside the guest OS, run netstat -rn
(or ipconfig
on a Windows guest) and look for the row with a destination IP of 0.0.0.0
(or the field labeled "Default Gateway" on Windows):
$ netstat -rn
Kernel IP routing table
Destination Gateway Genmask Flags MSS Window irtt Iface
0.0.0.0 10.0.2.2 0.0.0.0 UG 0 0 0 eth0
10.0.2.0 0.0.0.0 255.255.255.0 U 0 0 0 eth0
192.168.33.0 0.0.0.0 255.255.255.0 U 0 0 0 eth1
You can extract this IP programmatically with netstat -rn | grep "^0.0.0.0 " | tr -s ' ' | cut -d " " -f2
.
Sources: How to connect with host PostgreSQL from vagrant virtualbox machine; Connect to the host machine from a VirtualBox guest OS?