How to find out ip address of new virtual machine using libvirt 0.10.0+ (routed network)

dhcpdnsmasqkvm-virtualizationlibvirt

My goal is to find out ip address of new virtual machine by using libvirt api only (>=0.10). Currently I am using libvirt's net-update command: before start a new machine I set static dhcp entry for it and vm booting with known address.

It works almost fine even with old libvirt versions, but has a one bug. When I "force off" machine, it doesn't send "release" query to dhcp server (libvirt/dnsmasq) and this ip remains in leases file. If I create a new machine with same ip address before dhcp lease timed out, it won't get ip address from static entry, because dhcp server considers this ip is already used (based on information in lease file).

Are there any more robust solutions to get machine ip address or set it before start without shell access to target server or static network configuration inside virtual machine?

Best Answer

In the libvirt >= 1.2.14, it is possible to query libvirt to ask for the IP addresses that have been assigned to a guest NIC, avoiding the need to setup static IP addresses. e.g.

# virsh domifaddr f25kubdev
 Name       MAC address          Protocol     Address
-------------------------------------------------------------------------------
 vnet1      52:54:00:b4:fc:f2    ipv4         192.168.122.13/24

I'm not sure if that's any use to you though, since you mention libvirt 0.10.0

If you have >= 1.2.10 there's a less direct way to get the info by querying the DHCP lease database

# virsh net-dhcp-leases default
 Expiry Time          MAC address        Protocol  IP address                Hostname        Client ID or DUID
-------------------------------------------------------------------------------------------------------------------
 2017-01-19 12:01:01  52:54:00:b4:fc:f2  ipv4      192.168.122.13/24         f25kubdev       ff:00:b4:fc:f2:00:04:52:fb:4b:29:01:5e:44:c8:b6:57:85:dd:f2:7a:98:73

you then have to manually map the MAC address to the domain you're interested in - the 'domifaddr' command just does that mapping for you.

Prior to 1.2.10, there's no way to get this info via the libvirt API at all - you'd have to poke around in the dnsmasq leases file directly.