Beispiel #1
0
        public static unsafe NetworkInterface[] GetLinuxNetworkInterfaces()
        {
            var systemProperties = new LinuxNetworkInterfaceSystemProperties();

            int interfaceCount = 0;
            int addressCount   = 0;

            Interop.Sys.NetworkInterfaceInfo *nii = null;
            Interop.Sys.IpAddressInfo *       ai  = null;
            IntPtr globalMemory = (IntPtr)null;

            if (Interop.Sys.GetNetworkInterfaces(ref interfaceCount, ref nii, ref addressCount, ref ai) != 0)
            {
                string message = Interop.Sys.GetLastErrorInfo().GetErrorMessage();
                throw new NetworkInformationException(message);
            }

            globalMemory = (IntPtr)nii;
            try
            {
                NetworkInterface[] interfaces = new NetworkInterface[interfaceCount];
                Dictionary <int, LinuxNetworkInterface> interfacesByIndex = new Dictionary <int, LinuxNetworkInterface>(interfaceCount);

                for (int i = 0; i < interfaceCount; i++)
                {
                    var lni = new LinuxNetworkInterface(Marshal.PtrToStringAnsi((IntPtr)nii->Name) !, nii->InterfaceIndex, systemProperties);
                    lni._interfaceType     = (NetworkInterfaceType)nii->HardwareType;
                    lni._speed             = nii->Speed;
                    lni._operationalStatus = (OperationalStatus)nii->OperationalState;
                    lni._mtu = nii->Mtu;
                    lni._supportsMulticast = nii->SupportsMulticast != 0;

                    if (nii->NumAddressBytes > 0)
                    {
                        lni._physicalAddress = new PhysicalAddress(new ReadOnlySpan <byte>(nii->AddressBytes, nii->NumAddressBytes).ToArray());
                    }

                    interfaces[i] = lni;
                    interfacesByIndex.Add(nii->InterfaceIndex, lni);
                    nii++;
                }

                while (addressCount != 0)
                {
                    var address = new IPAddress(new ReadOnlySpan <byte>(ai->AddressBytes, ai->NumAddressBytes));
                    if (address.IsIPv6LinkLocal)
                    {
                        address.ScopeId = ai->InterfaceIndex;
                    }

                    if (interfacesByIndex.TryGetValue(ai->InterfaceIndex, out LinuxNetworkInterface? lni))
                    {
                        lni.AddAddress(address, ai->PrefixLength);
                    }

                    ai++;
                    addressCount--;
                }

                return(interfaces);
            }
            finally
            {
                Marshal.FreeHGlobal(globalMemory);
            }
        }
Beispiel #2
0
 internal LinuxNetworkInterface(string name, int index, LinuxNetworkInterfaceSystemProperties systemProperties) : base(name)
 {
     _index        = index;
     _ipProperties = new LinuxIPInterfaceProperties(this, systemProperties);
 }