Skip to content

Instantly share code, notes, and snippets.

@sfinktah
Created September 28, 2023 20:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sfinktah/600430dd71b0036bdcc3704171d72186 to your computer and use it in GitHub Desktop.
Save sfinktah/600430dd71b0036bdcc3704171d72186 to your computer and use it in GitHub Desktop.
UPNP external IP query for Asterisk in BASH
#!/usr/bin/env bash
function wan_ip_connection() {
local host=$1
result=$( curl -s "http://$host/upnp/control?WANIPConnection" \
-H 'SOAPAction: "urn:schemas-upnp-org:service:WANIPConnection:1#GetExternalIPAddress"' \
--data-binary '<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:GetExternalI
PAddress xmlns:u="urn:schemas-upnp-org:service:WANIPConnection:1"></u:GetExternalIPAddress></s:Body></s:Envelope>'
)
REGEX='ExternalIPAddress>([0-9.]+)<'
if [[ $result =~ $REGEX ]]
then
echo "${BASH_REMATCH[@]:1}"
fi
}
function initial_query() {
echo -e 'M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: "ssdp:discover"\r\nMX: 3\r\nST: urn:schemas-upnp-org:device:InternetGatewayDevice:1\r\n\r\n' |
socat STDIO UDP4-DATAGRAM:239.255.255.250:1900
}
function ip() {
location=$( initial_query | grep LOCATION )
location=${location%/*}
location=${location##*/}
ip=$( wan_ip_connection "$location" )
echo $ip
}
function get_existing_ip() {
# externip=121.221.66.178
REGEX='^externip=([0-9.]+)'
while read -r
do
if [[ $REPLY =~ $REGEX ]]
then
current_ip="${BASH_REMATCH[@]:1}"
current_ip=${current_ip#*=}
echo "$current_ip"
return
fi
done < /etc/asterisk/sip_general_custom.conf
}
old_ip=$( get_existing_ip )
new_ip=$( ip )
if test -n "$new_ip"; then
curl -q "http://nt4.com/gf/?ip=$new_ip"
if [[ $old_ip != $new_ip ]]
then
echo "changing ip from $old_ip to $new_ip"
echo "externip=$new_ip" > /etc/asterisk/sip_general_custom.conf
echo "localnet=192.168.1.0/24" >> /etc/asterisk/sip_general_custom.conf
# echo "port=5160" >> /etc/asterisk/sip_general_custom.conf
echo "bindport=5160" >> /etc/asterisk/sip_general_custom.conf
echo "nat=yes" >> /etc/asterisk/sip_general_custom.conf
# perl -pi -e "s/$old_ip/$new_ip/" /etc/asterisk/sip_general_custom.conf
service asterisk restart
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment