Monday, September 28, 2015

Find Guest IP from Host and Host IP from Guest in Virtual Machine



There are only couple of ways to communicate between guest and host. And if we want a hypervisor independent way of communication, using socket is the most feasible option. But to do that, the minimum thing we need is knowing the ip address of guests and host.

After a bit research, I found out an easy way of doing that. We can use utilities like arp-scan and arp, and that will make our life a lot easier. I will explain the details in a short while.

Before that, we need to install arp-scan in both guest and host.

# sudo apt-get install arp-scan

My host as well as guest is Ubuntu system. So, I will be using simple shell scripts to solve the purpose.

Write this shell script in Host:


#!/bin/bash
GUEST1="vm1-virtual-machine.local"
GUEST2="vm2-virtual-machine.local"
echo -e "Which VM?\n1.$GUEST1\n$GUEST2\n[1/2] \c"
read answer
if [ $answer -eq 1 ]
then
GUEST=$GUEST1
else
GUEST=$GUEST2
fi
echo "You want ip for $GUEST"

ip=`arp -a | grep $GUEST | awk '{print $2}'`

arr1=$(echo $ip | tr "(" "\n")
arr2=$(echo $arr1 | tr ")" "\n")
ip=$arr2

echo "Guest IP is:$ip”


Here, I am using arp -a in the host machine. If the arp table is populated properly, 'arp -a' will give hostname and ip of machines in local network. Irrespective of whether the guest VMs are having independent ip address (e.g. through bridge network), it will list the guest VMs and their ip addresses. We can filter out the ip address of the guest from its hostname. Yes, you need to know the hostname of the guests in advance.


In the guest, run the following script:

#!/bin/bash
echo -e "Interface (e.g. eth0, eth1 etc): \c"
read interface
IN=`sudo arp-scan --interface=$interface 192.168.1.1/24 | awk '{print $1,$2}' | grep <host MAC address>`
arr=$(echo $IN | tr " " "\n")
flag=0
for x in $arr
do
if [ $flag -eq 0 ]
then
#echo $x
ip=$x
flag=1
fi
done
echo "Host ip is $ip"



Here, I am doing an 'arp-scan' to find out all the ip addresses and MAC addresses in the local network. Now, filter out the host with its MAC address. Yes, you need to know the MAC address of the host in advance.


The advantage of a simple shell script like this is, you can run it in host and guests and run socket programming thereafter. This will automate the process of communication. And if you are using sockets, it gives an opportunity to share myriads of information.

So, this was a very simple shell script. I am quite a novice in shell scripts, but what I can say is, this works.

So, you can always borrow this idea and write your own shell scripts. And when you do that, please share your feedback. Good day!

No comments:

Post a Comment