How to change port forwardings during the SSH connection

Last year I wrote a short article about how to set up SSH port forwarding but I forgot to mention that you can quickly terminate existing port forwardings and create new ones during the SSH connection.

To access required SSH functions you need to use defined escape sequences:

$ ~?
Supported escape sequences:
  ~.  - terminate connection (and any multiplexed sessions)
  ~B  - send a BREAK to the remote system
  ~C  - open a command line
  ~R  - Request rekey (SSH protocol 2 only)
  ~^Z - suspend ssh
  ~#  - list forwarded connections
  ~&  - background ssh (when waiting for connections to terminate)
  ~?  - this message
  ~~  - send the escape character by typing it twice
(Note that escapes are only recognized immediately after newline.)

Port forwarding options:

$ ~C
ssh> 
Commands:
      -L[bind_address:]port:host:hostport    Request local forward
      -R[bind_address:]port:host:hostport    Request remote forward
      -D[bind_address:]port                  Request dynamic forward
      -KL[bind_address:]port                 Cancel local forward
      -KR[bind_address:]port                 Cancel remote forward
      -KD[bind_address:]port                 Cancel dynamic forward

Look at the following example to understand it better:

$ ssh somewhere
milosz@somewhere's password: XXXXXXXXXX
Linux somewhere 3.2.0-4-amd64 #1 SMP Debian 3.2.41-2 x86_64
$
$ ~C
ssh> -D 9999
Forwarding port.
$ ~#
The following connections are open:
  #0 client-session (t4 r0 i0/0 o0/0 fd 4/5 cc -1)
  #3 direct-tcpip: listening port 9999 for 1.2.3.4 port 80, connect from 127.0.0.1 port 44191 (t4 r1 i0/0 o0/0 fd 9/9 cc -1)
  #4 direct-tcpip: listening port 9999 for 1.2.3.4 port 80, connect from 127.0.0.1 port 44199 (t4 r2 i0/0 o0/0 fd 10/10 cc -1)
  #5 direct-tcpip: listening port 9999 for 4.3.2.1 port 80, connect from 127.0.0.1 port 44201 (t4 r3 i0/0 o0/0 fd 11/11 cc -1)
$ ~C
ssh> -KD 9999
Canceled forwarding.
$ ~.
Connection to somewhere closed.

More information can be found in the manual page:

$ man ssh
Milosz Galazka