Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Return valid MAC address in any situation #515

Merged
merged 1 commit into from
May 11, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
}