Skip to content

Commit

Permalink
Return valid MAC address in any situation
Browse files Browse the repository at this point in the history
  • Loading branch information
aaron-ai committed May 11, 2023
1 parent 9f9434b commit 12fe117
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
16 changes: 13 additions & 3 deletions csharp/rocketmq-client-csharp/Utilities.cs
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ public static class Utilities
private static long _instanceSequence = 0;
private static readonly int ProcessId = Process.GetCurrentProcess().Id;
private static readonly string HostName = System.Net.Dns.GetHostName();
private static readonly byte[] RandomMacAddressBytes =
Enumerable.Range(0, 6).Select(_ => (byte)new Random().Next(256)).ToArray();

public const int MasterBrokerId = 0;

public static int GetPositiveMod(int k, int n)
Expand All @@ -42,9 +45,16 @@ public static int GetPositiveMod(int k, int n)

public static byte[] GetMacAddress()
{
return NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nic =>
nic.OperationalStatus == OperationalStatus.Up &&
nic.NetworkInterfaceType != NetworkInterfaceType.Loopback)?.GetPhysicalAddress().GetAddressBytes();
var nic = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
x => x.OperationalStatus == OperationalStatus.Up &&
x.NetworkInterfaceType != NetworkInterfaceType.Loopback) ??
NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
x => x.OperationalStatus == OperationalStatus.Unknown &&
x.NetworkInterfaceType != NetworkInterfaceType.Loopback) ??
NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(
x => x.NetworkInterfaceType != NetworkInterfaceType.Loopback);

return nic != null ? nic.GetPhysicalAddress().GetAddressBytes() : RandomMacAddressBytes;
}

public static int GetProcessId()
Expand Down
7 changes: 7 additions & 0 deletions csharp/tests/UtilitiesTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,12 @@ public void TestComputeSha1Hash()
var bytes = Encoding.UTF8.GetBytes("foobar");
Assert.AreEqual(Utilities.ComputeSha1Hash(bytes), "8843D7F92416211DE9EBB963FF4CE28125932878");
}

[TestMethod]
public void TestGetMacAddress()
{
var macAddress = Utilities.GetMacAddress();
Assert.IsNotNull(macAddress);
}
}
}

0 comments on commit 12fe117

Please sign in to comment.