Tuesday, March 3, 2015

Is my code running inside virtual machine?

This is a small tip which rarely, we as programmers need to apply. Its about how to determine whether our code is running inside a virtual machine or not.Actually it doesn't matter if we are writing business applications. But in some cases especially when we are dealing with hardware devices we may need to disable some features by checking whether the code is under virtual machine. Also this is not a first thing any programmer is looking for. So I am aggregating links as well.

Native C++

Hope everyone will be aware of this as people who are in unmanaged world are talking directly to the computer.

.Net (C# or VB.Net)

In .Net the easiest way if to query the WMI objects. We can get easily get example code snippets from internet. Some are below.

http://stackoverflow.com/questions/498371/how-to-detect-if-my-application-is-running-in-a-virtual-machine

SQL

Query the DMV sys.dm_os_sys_info as follows

SELECT virtual_machine_type,virtual_machine_type_desc 
FROM sys.dm_os_sys_info

The sys.dm_os_sys_info gives much more information about the host system such as last SQL Server restart time, memory information etc...

There are different virtualization softwares available to create virtual machines. The method to determine that detail may vary from type to type. Need to invest some time to determine that.

No comments: