NAT with port forwarding on Virtual Box

You can use the host-only-adapter networking, if you require the virtual machine to be accessible only from the host machine. In this case your virtual machine will not have access to anywhere outside the host. Read more about virtual box networking at http://www.virtualbox.org/manual/ch06.html

On the other hand NAT enabled interface can communicate with clients outside the host, but the host cannot access the services on the virtual machine directly. We need to enabled port forwarding with NAT interface to achieve this.

On Linux:
If you need to have ssh accessible from host machine to virtual machine,

$ VBoxManage modifyvm "VM Name" --natpf1 "openssh,tcp,127.0.0.1,2222,,22"

Where –natpf1 is for adapter1, openssh is just a anme, and you can also input the ip address of virtual machine like

$ VBoxManage modifyvm "VM Name" --natpf1 "openssh,tcp,127.0.0.1,2222,10.0.2.20,22"

(assume the virtual machine ip is 10.0.2.20)

Now you can make ssh connection from host like, $ ssh localhost -p 2222

We can use same port number for port number about 1024 , say for a service running on port 8080 we can forward it with

VBoxManage modifyvm "VM Name" --natpf1 "proxy,tcp,127.0.0.1,8080,10.0.2.20,8080"

These rules will be added to the .VirtualBox/Machines/machine_name/machine_name.xml file like:
< Forwarding name="openssh" proto="1" hostip="127.0.0.1" hostport="2222" guestip=10.0.2.20 guestport="2222"/>

You can forward connection to any port on virtual host like this.

Make sure that the virtual machine interface is closed and the vm is not running while you change it, otherwise the changes will not take effect.

On Windows:

VBoxManage setextradata "VM Name" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guestssh/Protocol" TCP
VBoxManage setextradata "VM Name" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guestssh/GuestPort" 22
VBoxManage setextradata "VM Name" "VBoxInternal/Devices/pcnet/0/LUN#0/Config/guestssh/HostPort" 2222

* Replace VM Name with your virtual instance name

./arun

Leave a Reply

Your email address will not be published. Required fields are marked *


*