Sometimes we need to configure asterisk as a SIP client behind a NAT. Common ways to solve this NAT issue is configuring externip=xxx.xxx.xxx.xxx and localnet=xxx.xxx.xxx.xxx where this last localnet use the form:
;localnet=192.168.0.0/255.255.0.0; All RFC 1918 addresses are local networks
;localnet=10.0.0.0/255.0.0.0 ; Also RFC1918
;localnet=172.16.0.0/12 ; Another RFC1918 with CIDR notation
;localnet=169.254.0.0/255.255.0.0 ;Zero conf local network
or something like:
localnet=192.168.1.1/24;
Everything would be just fine is the
externip or External IP address remained always the same; but, some times this is not true because our ISP assigns us a dynamic public IP address that changes from time to time, or in the worst case a private IP address (like me).
To solve the previous issue we could, from time to time (really often), discover the new IP address and change the line externip=xxx.xxx.xxx.xxx in sip.conf file and issue a
sip reload command in asterisk
CLI; we could also use an automated procedure, as I did. A third option could be to use dyndns, something that cannot be done if you get a private IP address asigned.
I am going to explain how I solved this problem by using an automated procedure.
1. I changed the line
externip=xxx.xxx.xxx.xxx
for:
#include sip_externip.conf.
2. I wrote a script (with some help at the begining) that has changed. This is what I currently have (saved as
checkexternip):
--------------------------------------------------------------------
# Get external IP address.
mynewip=`wget -O - http://checkip.dyndns.com|cut -b77-92|tr -d "</body>"`
# Get current Asterisk IP address.
myoldip=`dd if=/etc/asterisk/sip_externip.conf bs=9 skip=1 2>null`
if test .$myoldip != .$mynewip && !(test -z $mynewip)
then echo "externip=$mynewip" > /etc/asterisk/sip_externip.conf
echo `date` "$mynewip" >> /etc/asterisk/sip_externip.log
asterisk -r -x "sip reload"
fi
-------------------------------------------------------------
This script checks for external IP changes, if changed rewrite sip_externip.conf, records the new IP address in sip_externip.log and asks asterisk to reaload sip configuration.
3. I wrote a cron entry like this:
*/1 * * * * /etc/asterisk/checkexternip
This cron entry executes the script once every minute so, my asterisk could be out of service (if my extern IP address changes) for maximum 1 minute. You must change /etc/asterisk/ with the path where you save your
checkexternip script.
I hope this procedure can be usefull to someone else.
Juan C.