How to connect to a VNC server in a remote local network (SSH tunneling)
Imagine you need to remotely help somebody and you need to connect to his computer. You can use the very nice teamviewer (free for personal use and it works under mac osx, windows and linux).
You can also use VNC, especially useful for example if you need to connect to your computer at work and nobody is available to start teamviewer, or you don’t want to give your password to somebody else, or you want to have a remote connection opened only when needed. It’s very easy to do if the remote computer has a public ip. But what if it doesn’t ?
Let’s imagine the case below: you are at home and you want to connect to “Computer A” at work, which only has a local address (for example computera.local). You can have access to the server from internet and it’s running linux. Computer A is also running linux (it’s doable with windows too).
First you need to install ssh on the server and Computer A sudo apt-get install ssh
Then connect to the server from your computer ssh myuser@server.example.com
(you can buy your own domain, use directly the ip address, or if you have a dynamic ip, use a dynamic DNS like www.duckdns.org)
From the server, connect to computer A ssh myuser@computera.local
(you can use the local ip here)
From computer A, start VNC. I use x11vnc, and the parameters depend on the display manager (gdm, lightdm, kdm, etc…) and if a session is already started or not. Here, the session is not started and we use lightdm under ubuntu 14.04: sudo x11vnc -xkb -noxrecord -noxfixes -noxdamage -display :0 -auth /var/run/lightdm/root/:0 -passwd MyPassword
So now you have a VNC server running in the local network but no way to connect from internet. So we have to create a tunnel from our computer to computer A in the local network through the server with SSH.
On your computer, open a new terminal and enter the following: ssh -N -L 5900:computera.local:5900 myuser@server.example.com
(5900 is VNC default port, 5900:computera.local:5900 means that the port 5900 on localhost will be forwarded to the port 5900 on computera.local)
Now you can access to the VNC server on computer A connecting to localhost:5900.
The SSH tunneling can be used for any port forwarding, for example if you want to connect to the web server running on your development machine, FTP, databases server…