Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 848
vaj oja Avatar asked May 18 '26 00:05

vaj oja


1 Answers

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
like image 89
glenn jackman Avatar answered May 20 '26 17:05

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!