Search code examples
shellnetwork-programmingawkgreparp

Add localhost's IP and MAC address to shell scripts


I use the following command to get the arp table. I now want to add the localhost's ip and MAC address to the output. How should I write the shell script?

arp | grep -v 'incomplete' | tail -n+2 | awk '{print $1"*"$4}'

So the results look like below(it adds iface and host ip to each line of arp table entry)

 eno16777736 192.168.140.133 192.168.140.254,00:50:56:ef:2d:57
 eno16777736 192.168.140.133 192.168.140.2,00:50:56:ea:cf:bf

Solution

  • On my system, I can do:

    arp | 
    awk 'NR>1{mac[$NF]=mac[$NF]" "$3} END {for (iface in mac) print iface, mac[iface]}' | 
    while read iface mac; do
        inet=$(
            ifconfig "$iface" |
            awk -v i=$iface '{for (j=1; j<NF; j++) if ($j == "inet") {print $(j+1); exit}}'
        )
        echo $iface $inet ${mac// /,}
    done