jscarle/HyperV.NET

Fetch MAC address of the created VM

Closed this issue · 1 comments

Is there any function in the VMMS class, that will help to fetch the MAC address of the recently created VM?

I was able to fetch the MAC address of the VM from the primary machine using the WMI APIs

private string FetchMACAddress(string vmName)
{
    string vmHost = Dns.GetHostName();
    string wmiNamespace = @"\\" + vmHost + @"\root\virtualization\v2";

    ManagementObject virtualMachine = this.GetVirtualMachine(vmName, wmiNamespace);
    ManagementScope vmScope = new ManagementScope(wmiNamespace);

    string nicQuery = "SELECT * FROM Msvm_SyntheticEthernetPortSettingData WHERE InstanceID LIKE '%" + virtualMachine.GetPropertyValue("Name").ToString() + "%'";
    using (ManagementObjectSearcher nicSearcher = new ManagementObjectSearcher(vmScope, new ObjectQuery(nicQuery)))
    {
        ManagementObjectCollection nicResults = nicSearcher.Get();
        ManagementObject nicResult = nicResults.OfType<ManagementObject>().FirstOrDefault();
        return nicResult.GetPropertyValue("Address").ToString();
    }
}

The ManagementObjectSearcher() helps to find all the nicCards/Switches associated with the Virtual Machine, which further helps to find the MAC Address of the Virtual Machine.