12

I set autoport=yes in a domain's("virtual machine" in libvirt) config file so the VNC port is assigned automatically in the run time.

I need to get this port so I can connect to the vm from outside, but I can't find the proper API to do so. Better in python because I'm using the libvirt-python bindings.

4 Answers 4

22

I have not found any API for the VNC port, not sure if the newer version of libvirt has this interface?

However, you can use the command virsh vncdisplay $domainName to show the port. NOTE: you must modify /etc/libvirt/qemu.conf enable vnc_listen='0.0.0.0'.

7

There's no API to get the VNC port. You have to take and parse the XML file to find out that port. Of course if the guest is destroyed (powered off/offline) that port will be a value of -1.

char * virDomainGetXMLDesc (virDomainPtr domain, unsigned int flags)

<domain>
  <devices>
    <graphics type='vnc' port='5900' autoport='yes'/>
  </devices>
</domain>

References

4

Here's how you do it in python, in case anyone needs this.

Save as vncport.py

from xml.etree import ElementTree as ET

import sys
import libvirt

conn = libvirt.open()

domain = conn.lookupByName(sys.argv[1])

#get the XML description of the VM
vmXml = domain.XMLDesc(0)
root = ET.fromstring(vmXml)

#get the VNC port
graphics = root.find('./devices/graphics')
port = graphics.get('port')

print port

Run Command

python vncport.py <domain name>
1
  • It's worth mentioning for clarity's sake because I wasn't and found this via trial-and-error: This value, since it's coming from the live XML info, will properly handle dynamic ports. So if the VM is 3rd VNC VM to start up, this XML definition will show 5902 as you would expect even if the base configuration is port=5000 autoport=yes. Dec 20, 2020 at 21:03
0

Here is one for the PHP version, if anyone needs this:

    $res = libvirt_domain_lookup_by_name($conn, $domname);
    $xmlString = libvirt_domain_get_xml_desc($res, '');

    $xml = simplexml_load_string($xmlString);
    $json = json_encode($xml);
    $data = json_decode($json,TRUE);

    $port = intval($data["devices"]["graphics"]["@attributes"]["port"]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.