Find out IP addresses from MACs in a Local Area Network

Devices connected in a LAN.
Image: Devices connected in a LAN. (License: CC-BY-SA Marcelo Canina)

Script for Linux to map all devices with their assigned IP in a LAN

Published:
Last modified:

Overview

This is a guide to know which IP address is assigned to which computer based in a mapping of device-MAC addresses.

In this way we can know which IP has been assigned by a DHCP server in a LAN, if we don’t have access to the DHCP server but we know the address of each device that can be connected.

1. Map IP and MACs

We need to have a list of DEVICE NAME - MAC like a comma separated values file ~/map-dev-mac.csv with three columns:

  • custom_dev_id: our assigned name to the device
  • mac: MAC address of the device
  • dev_name: the name set by the device itself

For example:

custom_dev_id,mac,dev_name
router,25:vj:b2:gk:9d:2f,tp-link
main-server,00:12:b2:d9:10:5a,zeus
mike-phone,54:ba:91:3d:d1:0b,REDMIphone

2. Install scanner

Install the scanner: arp-scan which will be used in the script.

sudo apt install arp-scan

2. Script

Now we use the following bash script lan-ips.sh:

#!/bin/bash

LOCAL_IP_MACS=$(sudo arp-scan --plain 192.168.1.0/24)
while read -r LINE; do
    # skip comments
    DEV_NAME=$(echo $LINE | cut -d',' -f1 -s)
    DEV_MAC=$(echo $LINE | cut -d',' -f2 -s)
    #if mac not empty
    if [ -n "$DEV_MAC" ]; then
	DEV_IP=`echo "$LOCAL_IP_MACS" | grep $DEV_MAC | cut -f1 # --zero-terminated `
	echo -e "$DEV_IP \t $DEV_NAME "
    fi
done < ~/map-dev-mac.csv

And make it executable: chmod +x lan-ips.sh

2.1 Note

Executing the script will look for all the devices connected in a LAN, typically 192.168.1.0/24, and then look each device in our text file, generating a list of IP-DEVICE_NAME

3. Example output

After executing the script:


$ lan-ips.sh
[sudo] password for user: 
 	 custom_dev_id 
192.168.1.1 	 router 
192.168.1.27     main-server
192.168.1.26     mike-phone

Conclusion

This is a simple way to access other devices when not having access to a DHCP server, it would need to be run often as the DHCP may assign new IPs to the devices connected in a LAN.

Feel free to propose any improvements to the script.

Uruguay
Marcelo Canina
I'm Marcelo Canina, a developer from Uruguay. I build websites and web-based applications from the ground up and share what I learn here.
comments powered by Disqus


How to know the IP address of each device in a LAN. Script for Linux

Clutter-free software concepts.
Translations English Español

Except as otherwise noted, the content of this page is licensed under CC BY-NC-ND 4.0 . Terms and Policy.

Powered by SimpleIT Hugo Theme

·