libvirt/virsh: How to list all domains/VMs with their IP addresses

virsh net-dhcp-leases default

Example output:

 Expiry Time           MAC address         Protocol   IP address          Hostname         Client ID or DUID
-----------------------------------------------------------------------------------------------------------------------------------------------------
 2025-02-05 02:11:17   4c:68:29:d5:aa:55   ipv4       192.168.122.73/24   abcdefghi-vm01   ff:b5:5e:67:ff:00:02:00:00:ab:11:53:fb:4f:97:fb:ea:c5:13
 2025-02-05 02:06:19   52:54:00:12:34:56   ipv4       192.168.122.76/24   test1234-vm      ff:40:56:63:a2:00:02:00:00:ab:11:39:d1:c8:61:96:3d:82:64
#!/bin/bash

# List all active domains
domains=$(virsh list --name | grep -v '^$')

echo "Domain Name   IP Address"
echo "-------------------------"

for domain in $domains; do
    # Fetch the IP address of the domain
    ip=$(virsh domifaddr "$domain" --source agent | awk '/ipv4/ {print $4}' | cut -d'/' -f1)
    
    # Fallback if no IP from guest agent
    if [ -z "$ip" ]; then
        ip=$(virsh domifaddr "$domain" | awk '/ipv4/ {print $4}' | cut -d'/' -f1)
    fi

    echo -e "$domain\t$ip"
done

Example output

Domain Name   IP Address
-------------------------
test-vm       192.168.122.100
web-server    192.168.122.101