Search code examples
cqemukvmlibvirt

Getting the KVM VM domain name in a C program using libvirt API


I'm writing a C program and I'd like to get the KVM VM's domain name. Is there an easy way to do that? I have the VM id of the machine and can get a pointer to the virDomainInfo struct. I know I can do it with the command, virsh domname <id>, but I can't seem to find a libvirt API so I can do it programmatically. After some digging I found the struct info for the virDomain. Would it be an option to grab it from there?

struct _virDomain {
   virObject object;
   virConnectPtr conn;                  /* pointer back to the connection */
   char *name;                          /* the domain external name */
   int id;                              /* the domain ID */
   unsigned char uuid[VIR_UUID_BUFLEN]; /* the domain unique identifier */
 };

below is the code I'm using.

virConnectPtr conn = virConnectOpen(connString);
virDomainPtr domainPtr = virDomainLookupByID(conn, vmid);

Not sure where to go from here. Thanks in advance for any help.


Solution

  • Just browsing through the libvirt API I found virDomainGetName, which seems like it may be exactly what you want:

    virDomainGetName

    const char * virDomainGetName (virDomainPtr domain)

    Get the public name for that domain

    domain a domain object Returns a pointer to the name or NULL, the string need not be deallocated its lifetime will be the same as the domain object.

    I through together some sample code:

      int main(int argc, char **argv) {
              virConnectPtr c;
              virDomainPtr d;
              char *name;
    
              c = virConnectOpen(NULL);
              d = virDomainLookupByID(c, 2);
              name = virDomainGetName(d);
    
              printf("name of domain %d is %s\n", 2, name);
              return 0;
      }