Who moved my Pi?

This is the scenario. You have a headless Raspberry Pi (i.e. without screen) and you want to connect to it through ssh. The problem is that you don’t know the IP address because it is a fresh install and you have not yet modified the IP settings.

There are several ways to find out the IP, I’ll propose two simple approaches (obviously you could always log into your router/switch and find out). Both solutions consist in listing all the IP address of your network before and after the Pi is on:

  1. Unplug the Raspberry Pi.
  2. Execute one of the following commands in the terminal:
    • a) Homemade solution:
      $ for n in $(seq 1 254); do (HOST=192.168.1.${n} ;ping -W 1 -c 1 -q $HOST &>/dev/null && echo $HOST UP) & done | grep -v '\['

    • b) Already made solution:
      $ fping -a -q -r 0 -g 192.168.1.0/24

  3. Plug the PI, execute again the command and spot the new IP address.

Using the above, you could write a one line command using diff to compare the IP addresses before and after connecting the Rasberry Pi. For instance, using fping:

dirA=$(fping -i 10 -r 1 -aAgq 192.168.1.0/24 | tee /dev/tty) && \
echo -e "\nPlug the Raspberry Pi, wait at least one minute and press enter"; read novar && \
dirB=$(fping -i 10 -r 1 -aAgq 192.168.1.0/24| tee /dev/tty) && \
echo -e "\nNew IP address found:"; \
diff <(echo "$dirA" | sort) <(echo "$dirB" | sort) && echo "  |-> None"

Notes:

  1. fping is not installed by default, you should install it first.
    (Arch Linux) # pacman -S fping
    (Ubuntu) $ sudo apt-get install fping

  2. Explanation of the for loop. The loop command is in parenthesis () and has an ampersand & at the end to run each ping in the background so we can launch in parallel the 254 pings instead of executing one after another and have to wait for each one of them to return (minimum one second if there is no respond). The final grep is to avoid displaying the job completion status (try to execute the command without grep and you’ll see what I mean).
    Advertisements
This entry was posted in Linux, network and tagged , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s