Running a server as a guest in a VirtualBox virtual machine isn’t much good when you can’t network with the guest OS from your host machine. Instead of setting up host interface networking, you can simply port forward though VirtualBox’s NAT. Once port forwarding is set up, any computer on your network will be able to network with your guest OS though forwarded ports on your host.

[update] The latest version of VirtualBox makes host interface networking simpler than this, so this post is not as useful now.

VirtualBox’s GUI doesn’t expose this functionality, but the VBoxManage command line utility does. Before starting, remember to close your virtual machine before changing it’s configuration.

You need five pieces of information:

  • your virtual machine’s name in VirtualBox
  • a descriptive name for your port forward
  • the guest port
  • the host port
  • the protocol to use (TCP or UDP).

These three terminal commands are used to set up the port forward (replace bold sections with your information):
VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/DescriptiveName/HostPort" HostPort

VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/DescriptiveName/GuestPort" GuestPort

VBoxManage setextradata GuestName "VBoxInternal/Devices/pcnet/0/LUN#0/Config/DescriptiveName/Protocol" Protocol

For example, to forward SSH traffic from “Ubuntu Intrepid” on port 22 to port 2222 on the host:
VBoxManage setextradata Ubuntu\ Intrepid "VBoxInternal/Devices/pcnet/0/LUN#0/Config/SSH/HostPort" 2222
VBoxManage setextradata Ubuntu\ Intrepid "VBoxInternal/Devices/pcnet/0/LUN#0/Config/SSH/GuestPort" 22
VBoxManage setextradata Ubuntu\ Intrepid "VBoxInternal/Devices/pcnet/0/LUN#0/Config/SSH/Protocol" TCP

In this case, you could now connect via SSH to the guest though port 2222 on the host:
ssh -p 2222 localhost

The guest is available from other machines on the network as well though the same port at the host’s IP address (if your firewall allows it).

You can set up as many port forwards as you wish, just keep changing your DescriptiveName value. To remove a port forward, repeat the same three commands again, but without the values:
VBoxManage setextradata Ubuntu\ Intrepid "VBoxInternal/Devices/pcnet/0/LUN#0/Config/SSH/HostPort"
VBoxManage setextradata Ubuntu\ Intrepid "VBoxInternal/Devices/pcnet/0/LUN#0/Config/SSH/GuestPort"
VBoxManage setextradata Ubuntu\ Intrepid "VBoxInternal/Devices/pcnet/0/LUN#0/Config/SSH/Protocol"

You can view the configuration for a virtual machine, including port forwards, with this command:
VBoxManage getextradata GuestName enumerate

One restriction you should be aware of is that you can’t use a host port lower than 1024 without running VirtualBox with escalated privilages.

Extra note: You can always access your host from inside your guest using the IP address if you need to do the reverse of this.

Related Posts