Skip to content

Instantly share code, notes, and snippets.

@donaldgray
Created January 12, 2016 23:13
Show Gist options
  • Save donaldgray/27ca1cb0f5607666e616 to your computer and use it in GitHub Desktop.
Save donaldgray/27ca1cb0f5607666e616 to your computer and use it in GitHub Desktop.
GetMachineIdentifier, used to identify machines in a cluster
using System;
using System.Net.NetworkInformation;
namespace ServiceLayer.Utilities.Identity
{
/// <summary>
/// Class used to get a unique machine identifier
/// </summary>
public static class MachineIdentifier
{
/// <summary>
/// Gets a unique machine identifier from the machines MAC address.
/// </summary>
/// <returns></returns>
public static uint GetMachineIdentifier()
{
// Get the first MAC address and use that as machine identifier.
var nics = NetworkInterface.GetAllNetworkInterfaces();
foreach (var adapter in nics)
{
var address = adapter.GetPhysicalAddress();
var bytes = address.GetAddressBytes();
if (bytes.Length > 0)
{
var uniqueId = BitConverter.ToUInt32(bytes, 0);
return uniqueId;
}
}
// No MAC addresses, return current timestamp.
return Convert.ToUInt32(DateTime.Now.TimeOfDay.TotalMilliseconds);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment