Ssh – How to detect IP of given device in same network

linuxnetworkingsshwifi

I have a very typical situation in which I want to connect an (android) phone to a linux notebook in the same (wifi) network using ssh. The IP's are assigned by DHCP so I know only the one of the client in advance. Knowing the IP of the client I could in principle loop a ssh command over all possible IP's in the same net to see if a server is listening there. However this seems highly inefficient. So, how can I figure out the IP of my host (knowing it's MAC address) so I can connect to it using ssh? I know about other software which achieves something like this so it must be possible. Related: can I dynamically assign a hostname to this IP on the client (assuming it is Linux) so that I can use a static entry in the ssh config file?

Best Answer

You can do it in the following two steps:

Step1:

Scan your subnet to fill your ARP cache. There are methods but I suggest fping. Install it on Ubuntu by running command bellow in a terminal:

apt-get install fping

...then scan your network (for example, subnet 192.168.10.0/24):

fping -g 192.168.10.0/24

Now the ARP cache is filled with MAC address of devices in your subnet.

Step2

Apply an appropriate filter on your ARP cache to just see target device. Just use following command (where aa:bb:cc:dd:ee:ff is the device's MAC):

arp -n | grep -i aa:bb:cc:dd:ee:ff | cut -c-15

The output is the IP address of target device.

EDIT1:

Sample MAC address has been changed to lower case because Linux shows it in this manner (unlike Microsoft Windows using upper case)

EDIT2:

Following bash script add an entry to hosts file (/etc/hosts) with name cellphone so you can access your device with name cellphone. To refresh associated IP address just run it again. Change name,mac and subnet to desired values.

#!/bin/sh
name="cellphone"
mac=aa:bb:cc:dd:ee:ff
subnet=192.168.10.0/24
fping -g ${subnet}
ip="$(arp -n | grep -i ${mac} | cut -c-15)"
sed -i".bak" '/'${name}'/d' /etc/hosts
if [ -z "$ip" ]; then
    echo "Device not found!"
else
    echo "${ip}\t${name}" >> /etc/hosts
fi
Related Question