Displaying your Raspberry Pi IP address on bootup

One of the problems of using RaspberryPi-based cars with Wifi connection is that even if you set them to auto-connect to a certain Wifi access point, you never know what their IP address will be, so you have to waste time search for them on the network. A good way to get around that (and to also display car information without having to SSH in via a terminal) is to mount a screen on the RaspberryPi, as shown above. I like the Adafruit 3.5″ TFT screen, which fits nicely on top of the Pi.

However, it’s not obvious how to get the screen to show your IP address once you connect, especially since the Wifi takes longer to connect than the Pi does to boot up, so any programs that run at bootup won’t be able to get the IP.  I searched for a while and then finally gave up and wrote it from scratch.  Here’s what you need to do:

First, edit the “crontab” file, which automatically runs programs at launch or at any frequency.  At the the command prompt, type “crontab -e”, which will ask you to select an editor. Select Nano, and add this line at the bottom of the file:

@reboot sleep 10; sudo python ip.py > /dev/tty1

Let me explain what that line does:

  1. The “@reboot” part says to do this once after every reboot.
  2. The “sleep 10;” part says to delay for ten seconds to give the Wifi time to connect.
  3. The “sudo python ip.py” part says to run a Python script called ip.py, which we’ll add next
  4. The “> /dev/tty1” part says to send the text output to the screen, which is called tty1.

Now we have to create the “ip.py” file that will display the IP address.  Type “sudo nano ip.py” to create the file and paste this:

import os
import socket
import fcntl
import struct

def get_ip_address(ifname):
 s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
 return socket.inet_ntoa(fcntl.ioctl(
 s.fileno(),
 0x8915, # SIOCGIFADDR
 struct.pack('256s', ifname[:15])
 )[20:24])

print("Wifi: ", get_ip_address('wlan0'))
print("Ethernet: ", get_ip_address('eth0'))

That’s it. Now the screen should show both the Wifi and Ethernet (if connected) addresses on bootup.