3

I'm looking for a way to use SCNetworkInterfaceCopyAll in my Xamarin.Mac app. I've imported it

[DllImport("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration")]
public static extern IntPtr SCNetworkInterfaceCopyAll();

Then I get an array by calling var array = NSArray.ArrayFromHandle<NSObject>(pointer). But can't figure out how to get values from the output array of SCNetworkInterface. I've tried to marshal it as

[StructLayout(LayoutKind.Sequential)]
public struct Test
{
    IntPtr interface_type;
    IntPtr entity_hardware;
}

And then call Marshal.PtrToStructure<Test>(i.Handle) but it gives random pointers instead of meaningful values.

Artur Shamsutdinov
  • 3,127
  • 3
  • 21
  • 39

3 Answers3

0

Can you use the information provided from System.Net.NetworkInformation. NetworkInterface (or do you need actually need a SCNetworkInterface?)

Xamarin.Mac Example:

foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
    if (nic.OperationalStatus == OperationalStatus.Up)
        Console.WriteLine(nic.GetPhysicalAddress());
}
Community
  • 1
  • 1
SushiHangover
  • 73,120
  • 10
  • 106
  • 165
0

Looking at SCNetworkConfiguration.h it appears there are a number of C APIs you are to call on your IntPtr to retrieve the specific information you need.

CoreFoundation APIs often return "baton" pointers that you need to pass to other functions. Where did you see that struct definition?

Chris Hamons
  • 1,510
  • 11
  • 22
0

You can use Objective-C methods in Xamarin to get the MAC Address as C# gives a different MAC Address:

[DllImport("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration")]
public static extern IntPtr SCNetworkInterfaceCopyAll();

[DllImport("/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration")]
public static extern IntPtr SCNetworkInterfaceGetHardwareAddressString(IntPtr scNetworkInterfaceRef);

private string MacAddress()
{
        string address = string.Empty;

        using (var interfaces = Runtime.GetNSObject<NSArray>(SCNetworkInterfaceCopyAll()))
        {
            for (nuint i = 0; i < interfaces.Count; i++)
            {
                IntPtr nic = interfaces.ValueAt(i);
                var addressPtr = SCNetworkInterfaceGetHardwareAddressString(nic);

                address = Runtime.GetNSObject<NSString>(addressPtr);

                if (address != null) break;
            }
        }
        return address;
}
Anoop Vaidya
  • 46,283
  • 15
  • 111
  • 140