Dynamically change title of FreeBSD terminal windows in SSH sessions

For a while I have been working on a FreeBSD 10 desktop, and one thing I missed from my Mac OS X Terminal was the ability to have the title bar of my terminal window change when I connect via SSH to a remote host. With a lot of SSH session in different windows opened at the same time, it becomes difficult to know what server you are sending commands to. Thus I solved this little annoyance by creating this alias in the .cshrc script:

alias remote 'printf \\033]0\;\%s\\007 "\!^" && ssh "\!*"'

I’m using the urxvt terminal, but I guess the solution can works well on any other UNIX terminal emulator for X11 out there.

At the same time, I found useful to have replicated in the title bar the same info I have in the prompt, thus I added the following lines to same configuration file, under the section that (in the default FreeBSD setup) checks if this is an interactive shell:

if ($?prompt) then
  ...
  if ( $?TERM ) then
   set prompt="%{\033]0;%N@%m:%~\007%}%N@%m:%c3 %# "
   endif
endif

(In bold the code I added).