Friday, November 08, 2013

Getting IP and MACs for hosts in a network without using nmap

Well, sometimes you need to find out which IPs in a given network are being used and what is the MAC addresses associated with them. Perhaps you want to make sure the machines are the ones that should be there (MAC spoofing notwithstanding). Or, as it happened to me before, you need to see which IPs your dhcp server have given out are actually being used. You can come up with other reasons too, even if they arenot honorable! Impress your friends! Be the life of the party!

Anyway, you can do some of this using nmap, but what if it is not available or you just want to use common Linux household commands? I have done something like this before using nslookup, but since dig is supposed to replace it, how about if we rewrite my old cold to use it? So, let's say you want to know what is in 10.0.0/24? You could do something like:

for i in $(seq 1 254)
  do ans=`ping -qnc 1 $subnet.$i | grep -c '100% packet loss'`
  [ "$ans" == 1 ] || echo "(+) $subnet.$i (`dig -x $subnet.$i +short` `arp -an $subnet.$i|awk '{ print $4 }'`) "

Or something a bit fancier, which would ask you to enter the first 3 octets of the network:

nonono() {
  printf "Enter subnet (only the first 3 octets): "
  read subnet
  for i in $(seq 1 254)
    do ans=`ping -qnc 1 $subnet.$i | grep -c '100% packet loss'`
    [ "$ans" == 1 ] || echo "(+) $subnet.$i (`dig -x $subnet.$i +short` `arp -an $subnet.$i|awk '{ print $4 }'`) "

Here is the code in action:

raub@desktop:~$ nonono
Enter subnet (only the first 3 octets): 10.0.0
(+) (router. 00:24:54:9s:2a:12) 
(+) ( 64:6b:b3:b0:76:e1) 
(+) ( 02:50:4d:c4:17:1a) 
(+) ( 02:50:4d:c4:17:1a) 
(+) ( bc:5f:f4:ad:d7:8d) 
(+) ( c0:ff:ee:4f:96:a9) 
(+) ( 00:9f:f3:46:23:90) 
(+) ( c0:ff:ee:67:1c:3c) 
(+) ( entries) 

Some stuff worth mentioning:

  1. Some machines have MAC beginning with c0:ff:ee. Those are VMs of mine running of vmhost; I use that so I can quickly identify them as VMs; you might want to follow the same idea if you have to deal with large amounts of VMs in server rooms.
  2. cookie and tomato have the same MAC. The reason is they are the same machine. I just configured its interface to do interface aliasing (eth0:0 and eth0:1 for instance) so one IP could be for a fileserver and another for a web server (really bad idea, which is why I thought you would like it). You can read about it in, say, here.
  3. Do note what we are calling subnet really isn't; it is just the first 3 octets in a class C network. In other words, it assumes your network is of the type a.b.c.0/24. You could change the code to handle any network provided the network IP and subnet mask; I will leave that as an exercise to you.
  4. If you want to run it in OSX, use arp -n instead of arp -an.

No comments: