Using Twitter to get the current IP address of your Raspberry Pi

The Raspbery Pi can act as a rather neat server due to its low power consumption and its flexibility. As it is very small and can be powered with a standard dell phone charger, its convenient to take it with you. But running in headless mode (i.e. no monitor is attached) and without a keyboard connected it can be a pain to “find” the device in a network as it receives a dynamic IP address whenever it gets connected via ethernet or wifi. Usually you just want to have a SSH console, so I wrote a little script based on ttytter, a Perl twitter client which tweets the current device IP address as soon as a connection is established. All you need is a Pi, Perl and a Twitter account.

Change to the root account, get the ttytter script, rename it and make it executable:

cd /opt/
mv 2.1.00.txt
chmod +x

Now execute the script and follow the instructions. You will open the Twitter OAuth page where you receive a PIN which authenticates the ttytter application with your account so that it can tweet updates. It will place a keyfile with the credentials in /.root/.keyfile. Copy this file to /opt/

Next we create a little script which parses the IP address currently assigned, I got it from here. Open a editor and save the file with the name The Raspberry Pi does not have a hardware clock, hence it does not know the time. Having the exact time is essential for the Twitter API, therefore we use ntpdate in order to set the correct time before we call the API.  After receiving the current time, the script calls the ttytter Twitter client and submits a tweet with the current IP address. Don’t forget the shebang in the beginning of the file and to make it executable with chmod +x.


# Parse the IP adress
while IFS=$': \t' read -a line ;do
    [ -z "${line%inet}" ] && ip=${line[${#line[1]}>4?1:2]} &&
        [ "${ip#}" ] && myip=$ip
  done< <(LANG=C /sbin/ifconfig)

# Get current time from NTP server
ntpdate -q
# Store current time
DATE=$(date +"%Y-%m-%d  %H:%M:%S")
#Tweet the IP address
echo -e "The pi just got $myip assigned at $DATE" | /opt/ -ssl -keyf=/opt/ttytterkey >/opt/tweetlog.txt 2>&1

We want that script to be called whenever a new network connection has been established. Hence we simply add the script to the post-up hook of the network interfaces. This hook is called after an interface has been connected.

auto lo

iface lo inet loopback
iface eth0 inet dhcp
post-up /opt/

allow-hotplug wlan0
iface wlan0 inet manual
wpa-roam /etc/wpa_supplicant/wpa_supplicant.conf
iface default inet dhcp
post-up /opt/

This script obviously assumes that an Internet connection is available and it does not implement any checks in case there is no connectivity. Knowing which IP address got assigned can be useful in many scenarios and is not limited to the Pi.

Continue reading