title: C/C++ How to get Processor Serial Number on linux
body: <p>I was wondering how to reliably obtain the Processor Serial Number (PSN) on GNU Linux.</p>
  
  <p>For now I'm using this</p>
  
  <pre class="lang-c prettyprint-override"><code>#include &lt;stdio.h&gt;
  #include &lt;cpuid.h&gt;
  
  unsigned int level = 1;
  unsigned eax = 3 /* processor serial number */, ebx = 0, ecx = 0, edx = 0;
  __get_cpuid(level, &amp;eax, &amp;ebx, &amp;ecx, &amp;edx);
  
  // byte swap
  int first = ((eax &gt;&gt; 24) &amp; 0xff) | ((eax &lt;&lt; 8) &amp; 0xff0000) | ((eax &gt;&gt; 8) &amp; 0xff00) | ((eax &lt;&lt; 24) &amp; 0xff000000);
  int last = ((edx &gt;&gt; 24) &amp; 0xff) | ((edx &lt;&lt; 8) &amp; 0xff0000) | ((edx &gt;&gt; 8) &amp; 0xff00) | ((edx &lt;&lt; 24) &amp; 0xff000000);
  
  printf("PSN: %08X%08X", first, last);
  </code></pre>
  
  <p>It gives me <code>PSN: A7060200FFFBEBBF</code>,<br>
  which matches with  </p>
  
  <pre class="lang-bash prettyprint-override"><code>sudo dmidecode | grep -P '^\s+ID: ([0-9A-F]{2} ){7}[0-9A-F]{2}$'
  </code></pre>
  
  <p>output: <code>ID: A7 06 02 00 FF FB EB BF</code></p>
  
  <p>I only tested on Intel Core i processors, so perhaps it's only working for this type of CPU.</p>
  
  <p>I know that the "Serial Number" is the same across identical CPU model, and is thus not unique.</p>
  
  <p>Also, I'm looking forward for a way of achieving that, that does not rely on executing a shell command and parsing the output.</p>