Return valid MAC address in any situation (#515)
diff --git a/csharp/rocketmq-client-csharp/Utilities.cs b/csharp/rocketmq-client-csharp/Utilities.cs
index ca334b9..6d74777 100644
--- a/csharp/rocketmq-client-csharp/Utilities.cs
+++ b/csharp/rocketmq-client-csharp/Utilities.cs
@@ -32,6 +32,9 @@
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)
@@ -42,9 +45,16 @@
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()
diff --git a/csharp/tests/UtilitiesTest.cs b/csharp/tests/UtilitiesTest.cs
index 5c82fca..ed45bce 100644
--- a/csharp/tests/UtilitiesTest.cs
+++ b/csharp/tests/UtilitiesTest.cs
@@ -46,5 +46,12 @@
var bytes = Encoding.UTF8.GetBytes("foobar");
Assert.AreEqual(Utilities.ComputeSha1Hash(bytes), "8843D7F92416211DE9EBB963FF4CE28125932878");
}
+
+ [TestMethod]
+ public void TestGetMacAddress()
+ {
+ var macAddress = Utilities.GetMacAddress();
+ Assert.IsNotNull(macAddress);
+ }
}
}
\ No newline at end of file