コード例 #1
0
        GetInterfaceIndex(string iface, AddressFamily family)
        {
            if (iface.Length == 0)
            {
                return(-1);
            }

            //
            // The iface parameter must either be an IP address, an
            // index or the name of an interface. If it's an index we
            // just return it. If it's an IP addess we search for an
            // interface which has this IP address. If it's a name we
            // search an interface with this name.
            //
            try
            {
                return(int.Parse(iface, CultureInfo.InvariantCulture));
            }
            catch (FormatException)
            {
            }

            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            try
            {
                var addr = IPAddress.Parse(iface);
                foreach (NetworkInterface ni in nics)
                {
                    IPInterfaceProperties ipProps = ni.GetIPProperties();
                    foreach (UnicastIPAddressInformation uni in ipProps.UnicastAddresses)
                    {
                        if (uni.Address.Equals(addr))
                        {
                            if (addr.AddressFamily == AddressFamily.InterNetwork)
                            {
                                IPv4InterfaceProperties ipv4Props = ipProps.GetIPv4Properties();
                                if (ipv4Props != null)
                                {
                                    return(ipv4Props.Index);
                                }
                            }
                            else
                            {
                                IPv6InterfaceProperties ipv6Props = ipProps.GetIPv6Properties();
                                if (ipv6Props != null)
                                {
                                    return(ipv6Props.Index);
                                }
                            }
                        }
                    }
                }
            }
            catch (FormatException)
            {
            }

            foreach (NetworkInterface ni in nics)
            {
                if (ni.Name == iface)
                {
                    IPInterfaceProperties ipProps = ni.GetIPProperties();
                    if (family == AddressFamily.InterNetwork)
                    {
                        IPv4InterfaceProperties ipv4Props = ipProps.GetIPv4Properties();
                        if (ipv4Props != null)
                        {
                            return(ipv4Props.Index);
                        }
                    }
                    else
                    {
                        IPv6InterfaceProperties ipv6Props = ipProps.GetIPv6Properties();
                        if (ipv6Props != null)
                        {
                            return(ipv6Props.Index);
                        }
                    }
                }
            }

            throw new ArgumentException("couldn't find interface `" + iface + "'");
        }
コード例 #2
0
 internal IPProperty(IPv6InterfaceProperties properties)
 {
     Mtu   = properties.Mtu;
     Index = properties.Index;
 }
コード例 #3
0
        public void networkProc()
        {
            NetworkInterface nic = nicArr[comboBoxDevice.SelectedIndex];

            IPGlobalProperties globalProperties = IPGlobalProperties.GetIPGlobalProperties();

            ArrayList info = new ArrayList();

            info.Add("Interfafce Information for:" + globalProperties.NodeType
                     + globalProperties.DomainName);
            info.Add("NetBIOS node type: " + globalProperties.NodeType);
            info.Add("===============================================");
            info.Add("Name: " + nic.Name);
            info.Add("Description: " + nic.Description);
            info.Add("Network Interface Type: " + nic.NetworkInterfaceType);
            info.Add("Physical Address: " + nic.GetPhysicalAddress().ToString());
            info.Add("Adapter ID: " + nic.Id);
            info.Add("Receive Only: " + nic.IsReceiveOnly);
            info.Add("Status: " + nic.OperationalStatus.ToString());
            info.Add("Speed: " + nic.Speed.ToString());

            IPInterfaceProperties properties = nic.GetIPProperties();

            info.Add("Properties: ");

            info.Add("|DNS Addresses");
            foreach (IPAddressInformation uniCast in properties.UnicastAddresses)
            {
                info.Add("->:" + uniCast.Address.ToString());
            }

            info.Add("|AnyCast Addresses");
            foreach (IPAddressInformation anyCast in properties.AnycastAddresses)
            {
                info.Add("->:" + anyCast.Address.ToString());
            }

            info.Add("|Support multi-cast: " + nic.SupportsMulticast);

            info.Add("|Multicast Addresses: ");
            foreach (IPAddressInformation multiCast in properties.MulticastAddresses)
            {
                info.Add("->: " + multiCast.Address.ToString());
            }

            info.Add("|Gateway Address");
            foreach (GatewayIPAddressInformation gateway in properties.GatewayAddresses)
            {
                info.Add("->:" + gateway.Address.ToString());
            }

            if (nic.Supports(NetworkInterfaceComponent.IPv4) == true)
            {
                IPv4InterfaceProperties ipv4 = properties.GetIPv4Properties();
                info.Add("+IPV4 Properties");
                if (ipv4 != null)
                {
                    info.Add("  |Interface Index : " + ipv4.Index.ToString());
                    info.Add("  |Automatic Private Addressing Active : " + ipv4.IsAutomaticPrivateAddressingActive.ToString());
                    info.Add("  |Automatic Private Addressing Enabled : " + ipv4.IsAutomaticPrivateAddressingEnabled.ToString());
                    info.Add("  |DHCP Enabled : " + ipv4.IsDhcpEnabled.ToString());
                    info.Add("  |Forwadding Enabled: " + ipv4.IsForwardingEnabled.ToString());
                    info.Add("  |MTU Size : " + ipv4.Mtu.ToString());
                    info.Add("  |\\Uses Wins : " + ipv4.UsesWins.ToString());
                }
                else
                {
                    info.Add("|Device has no IPV4 properties");
                }
            }
            else
            {
                info.Add(" |+IPv4 is not implemented: ");
            }


            if (nic.Supports(NetworkInterfaceComponent.IPv6) == true)
            {
                IPv6InterfaceProperties ipv6 = properties.GetIPv6Properties();
                info.Add(" +IPV6 Properties");

                if (ipv6 != null)
                {
                    info.Add("  +IPV6 Properties : ");
                    info.Add("  |Interface Index : " + ipv6.Index.ToString());
                    info.Add("  \\MTU Size : " + ipv6.Mtu.ToString());
                }
                else
                {
                    info.Add(" |Device has no IPV6 properties");
                }
            }

            else
            {
                info.Add(" +IPv6 is not Implemented");
            }

            foreach (string a in info)
            {
                listBoxDetail.Items.Add(a);
            }
        }
コード例 #4
0
 public static IIPv6InterfaceProperties ToInterface([CanBeNull] this IPv6InterfaceProperties properties)
 {
     return((properties == null) ? null : new IPv6InterfacePropertiesAdapter(properties));
 }
コード例 #5
0
ファイル: Network.cs プロジェクト: mreinart/ice
        private static IPAddress?GetInterfaceAddress(string iface, AddressFamily family)
        {
            Debug.Assert(iface.Length > 0);

            // The iface parameter must either be an IP address, an index or the name of an interface. If it's an index
            // we just return it. If it's an IP address we search for an interface which has this IP address. If it's a
            // name we search an interface with this name.
            try
            {
                return(IPAddress.Parse(iface));
            }
            catch (FormatException)
            {
            }

            NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
            try
            {
                int index = int.Parse(iface, CultureInfo.InvariantCulture);
                foreach (NetworkInterface ni in nics)
                {
                    IPInterfaceProperties ipProps = ni.GetIPProperties();
                    int interfaceIndex            = -1;
                    if (family == AddressFamily.InterNetwork)
                    {
                        IPv4InterfaceProperties ipv4Props = ipProps.GetIPv4Properties();
                        if (ipv4Props != null && ipv4Props.Index == index)
                        {
                            interfaceIndex = ipv4Props.Index;
                        }
                    }
                    else
                    {
                        IPv6InterfaceProperties ipv6Props = ipProps.GetIPv6Properties();
                        if (ipv6Props != null && ipv6Props.Index == index)
                        {
                            interfaceIndex = ipv6Props.Index;
                        }
                    }
                    if (interfaceIndex >= 0)
                    {
                        foreach (UnicastIPAddressInformation a in ipProps.UnicastAddresses)
                        {
                            if (a.Address.AddressFamily == family)
                            {
                                return(a.Address);
                            }
                        }
                    }
                }
            }
            catch (FormatException)
            {
            }

            foreach (NetworkInterface ni in nics)
            {
                if (ni.Name == iface)
                {
                    IPInterfaceProperties ipProps = ni.GetIPProperties();
                    foreach (UnicastIPAddressInformation a in ipProps.UnicastAddresses)
                    {
                        if (a.Address.AddressFamily == family)
                        {
                            return(a.Address);
                        }
                    }
                }
            }

            throw new ArgumentException($"couldn't find interface `{iface}'");
        }
コード例 #6
0
ファイル: Base.cs プロジェクト: Prinzessor/WinLLDPService
        /// <summary>
        /// Generate LLDP packet for adapter
        /// </summary>
        /// <param name="adapter"></param>
        private Packet CreateLLDPPacket(NetworkInterface adapter, PacketInfo pinfo)
        {
            Debug.IndentLevel = 2;

            PhysicalAddress MACAddress = adapter.GetPhysicalAddress();

            IPInterfaceProperties ipProperties = adapter.GetIPProperties();
            IPv4InterfaceProperties ipv4Properties = null; // Ipv4
            IPv6InterfaceProperties ipv6Properties = null;// Ipv6

            // IPv6
            if (adapter.Supports(NetworkInterfaceComponent.IPv6))
            {
                try
                {
                    ipv6Properties = ipProperties.GetIPv6Properties();
                }
                catch (NetworkInformationException e)
                {
                    // Adapter doesn't probably have IPv6 enabled
                    Debug.WriteLine(e.Message, EventLogEntryType.Warning);
                }
            }

            // IPv4
            if (adapter.Supports(NetworkInterfaceComponent.IPv4))
            {
                try
                {
                    ipv4Properties = ipProperties.GetIPv4Properties();
                }
                catch (NetworkInformationException e)
                {
                    // Adapter doesn't probably have IPv4 enabled
                    Debug.WriteLine(e.Message, EventLogEntryType.Warning);
                }
            }


            // System description
            Dictionary<string, string> systemDescription = new Dictionary<string, string>();
            systemDescription.Add("OS", pinfo.OperatingSystem);
            //systemDescription.Add("Ver", pinfo.OperatingSystemVersion);
            //systemDescription.Add("Usr", pinfo.Username);
            systemDescription.Add("Up", pinfo.Uptime);

            // Port description
            Dictionary<string, string> portDescription = new Dictionary<string, string>();

            // adapter.Description is for example "Intel(R) 82579V Gigabit Network Connection"
            // Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\NetworkCards\<number>\Description value
            //jt
            //portDescription.Add("Vendor", adapter.Description);
            //portDescription.Add("Vendor", "");

            /*
             adapter.Id is GUID and can be found in several places: 
             In this example it is "{87423023-7191-4C03-A049-B8E7DBB36DA4}"
            
             Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion
             - \NetworkCards\<number>\ServiceName value (in same tree as adapter.Description!)
             - \NetworkList\Nla\Cache\Intranet\<adapter.Id> key
             - \NetworkList\Nla\Cache\Intranet\<domain>\<adapter.Id> key
            
             Registry: HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows NT\CurrentVersion
             - \NetworkCards\<number>\ServiceName value
            
             Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Class\{4D36E972-E325-11CE-BFC1-08002BE10318}\0007
               {4D36E972-E325-11CE-BFC1-08002BE10318} == Network and Sharing Center -> viewing adapter's "Properties" and selecting "Device class GUID" from dropdown menu
               {4D36E972-E325-11CE-BFC1-08002BE10318}\0007 == Network and Sharing Center -> viewing adapter's "Properties" and selecting "Driver key" from dropdown menu
             - \NetCfgInstanceId value
             - \Linkage\Export value (part of)
             - \Linkage\FilterList value (part of)
             - \Linkage\RootDevice value 
            
             Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\DeviceClasses\{ad498944-762f-11d0-8dcb-00c04fc3358c}\##?#PCI#VEN_8086&DEV_1503&SUBSYS_849C1043&REV_06#3&11583659&0&C8#{ad498944-762f-11d0-8dcb-00c04fc3358c}\#{87423023-7191-4C03-A049-B8E7DBB36DA4}\SymbolicLink value (part of)
             Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\{ 4D36E972 - E325 - 11CE - BFC1 - 08002BE10318}\{ 87423023 - 7191 - 4C03 - A049 - B8E7DBB36DA4}
             Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Network\{4D36E972-E325-11CE-BFC1-08002BE10318}\{ACB3F7A0-2E45-4435-854A-A4E120477E1D}\Connection\Name value (part of)
             Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\{ 87423023 - 7191 - 4C03 - A049 - B8E7DBB36DA4}
             Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\iphlpsvc\Parameters\Isatap\{ ACB3F7A0 - 2E45 - 4435 - 854A - A4E120477E1D}\InterfaceName value (part of)
            
             Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\<various names>\Linkage
             - \Bind value (part of)
             - \Export value (part of)
             - \Route value (part of)
            
            Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\NetBT\Parameters\Interfaces\Tcpip_{87423023-7191-4C03-A049-B8E7DBB36DA4}
            Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Psched\Parameters\NdisAdapters\{87423023-7191-4C03-A049-B8E7DBB36DA4}
            Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\RemoteAccess\Interfaces\<number>\InterfaceName value
            Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Adapters\{87423023-7191-4C03-A049-B8E7DBB36DA4}\IpConfig value (part of)

            IPv4 information:
            Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\Tcpip\Parameters\Interfaces\{87423023-7191-4C03-A049-B8E7DBB36DA4}

            IPv6 information:
            Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters\Interfaces\{87423023-7191-4c03-a049-b8e7dbb36da4}

            Registry: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\WfpLwf\Parameters\NdisAdapters\{87423023-7191-4C03-A049-B8E7DBB36DA4}

            */
            // jt
            //portDescription.Add("ID", adapter.Id);
            //portDescription.Add("ID", "");

            // Gateway
            if (ipProperties.GatewayAddresses.Count > 0)
            {
                portDescription.Add("GW", String.Join(", ", ipProperties.GatewayAddresses.Select(i => i.Address.ToString()).ToArray()));
            }
            else
            {
                portDescription.Add("GW", "-");
            }

            // CIDR
            if (ipProperties.UnicastAddresses.Count > 0)
            {
                int[] mask = ipProperties.UnicastAddresses
                    .Where(
                      w => w.IPv4Mask.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork
                    )
                    .Select(x => getCIDRFromIPMaskAddress(x.IPv4Mask))
                    .Where( m => m!= 0)
                    .ToArray()
                    ;


                portDescription.Add("NM", String.Join(", ", mask));
            }
            else
            {
                portDescription.Add("NM", "-");
            }

            /*
            // DNS server(s)
            if (ipProperties.DnsAddresses.Count > 0)
            {
                portDescription.Add("DNS", String.Join(", ", ipProperties.DnsAddresses.Select(i => i.ToString()).ToArray()));
            }
            else
            {
                portDescription.Add("DNS", "-");
            }
            */

            // DHCP server
            if (ipProperties.DhcpServerAddresses.Count > 0)
            {
                portDescription.Add("DHCP", String.Join(", ", ipProperties.DhcpServerAddresses.Select(i => i.ToString()).ToArray()));
            }
            else
            {
                portDescription.Add("DHCP", "-");
            }

            /*
            // WINS server(s)
            if (ipProperties.WinsServersAddresses.Count > 0)
            {
                portDescription.Add("WINS", String.Join(", ", ipProperties.WinsServersAddresses.Select(i => i.ToString()).ToArray()));
            }
            */

            // Link speed
            portDescription.Add("Spd", ReadableSize(adapter.Speed) + "ps");

            // Capabilities enabled
            List<CapabilityOptions> capabilitiesEnabled = new List<CapabilityOptions>();
            capabilitiesEnabled.Add(CapabilityOptions.StationOnly);

            if (ipv4Properties.IsForwardingEnabled)
            {
                capabilitiesEnabled.Add(CapabilityOptions.Router);
            }

            ushort expectedSystemCapabilitiesCapability = GetCapabilityOptionsBits(GetCapabilityOptions());
            ushort expectedSystemCapabilitiesEnabled = GetCapabilityOptionsBits(capabilitiesEnabled);

            // Constuct LLDP packet 
            LLDPPacket lldpPacket = new LLDPPacket();
            lldpPacket.TlvCollection.Add(new ChassisID(ChassisSubTypes.MACAddress, MACAddress));
            lldpPacket.TlvCollection.Add(new PortID(PortSubTypes.LocallyAssigned, System.Text.Encoding.UTF8.GetBytes(adapter.Name)));
            lldpPacket.TlvCollection.Add(new TimeToLive(120));
            lldpPacket.TlvCollection.Add(new PortDescription(CreateTlvString(portDescription)));
            lldpPacket.TlvCollection.Add(new SystemName(GetFQDN()));
            lldpPacket.TlvCollection.Add(new SystemDescription(CreateTlvString(systemDescription)));
            lldpPacket.TlvCollection.Add(new SystemCapabilities(expectedSystemCapabilitiesCapability, expectedSystemCapabilitiesEnabled));

            // Management
            var managementAddressObjectIdentifier = "Management";

            // Add management IPv4 address(es)
            if (null != ipv4Properties)
            {
                foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses)
                {
                    if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                    {
                        lldpPacket.TlvCollection.Add(new ManagementAddress(new NetworkAddress(ip.Address), InterfaceNumbering.SystemPortNumber, Convert.ToUInt32(ipv4Properties.Index), managementAddressObjectIdentifier));
                    }
                }
            }

            // Add management IPv6 address(es)
            if (null != ipv6Properties)
            {
                foreach (UnicastIPAddressInformation ip in ipProperties.UnicastAddresses)
                {
                    if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                    {
                        lldpPacket.TlvCollection.Add(new ManagementAddress(new NetworkAddress(ip.Address), InterfaceNumbering.SystemPortNumber, Convert.ToUInt32(ipv6Properties.Index), managementAddressObjectIdentifier));
                    }
                }
            }

            // == Organization specific TLVs

            // Ethernet
            lldpPacket.TlvCollection.Add(new OrganizationSpecific(new byte[] { 0x0, 0x12, 0x0f }, 5, new byte[] { 0x5 }));

            var expectedOrganizationUniqueIdentifier = new byte[3] { 0, 0, 0 };
            var expectedOrganizationSpecificBytes = new byte[] { 0, 0, 0, 0 };

            //int orgSubType = 0;

            // IPv4 Information:
            //if (null != ipv4Properties)
            //{
            //    lldpPacket.TlvCollection.Add((new StringTLV(TLVTypes.OrganizationSpecific, String.Format("IPv4 DHCP: {0}", ipv4Properties.IsDhcpEnabled.ToString()))));
            //lldpPacket.TlvCollection.Add(new OrganizationSpecific(expectedOrganizationSpecificBytes, new StringTLV(), System.Text.Encoding.UTF8.GetBytes(String.Format("IPv4 DHCP: {0}", ipv4Properties.IsDhcpEnabled.ToString()))));
            //}

            // End of LLDP packet
            lldpPacket.TlvCollection.Add(new EndOfLLDPDU());

            if (0 == lldpPacket.TlvCollection.Count)
            {
                throw new Exception("Couldn't construct LLDP TLVs.");
            }

            if (lldpPacket.TlvCollection.Last().GetType() != typeof(EndOfLLDPDU))
            {
                throw new Exception("Last TLV must be type of 'EndOfLLDPDU'!");
            }

            foreach (TLV tlv in lldpPacket.TlvCollection)
            {
                Debug.WriteLine(tlv.ToString(), EventLogEntryType.Information);
            }

            // Generate packet
            Packet packet = new EthernetPacket(MACAddress, destinationHW, EthernetPacketType.LLDP);
            packet.PayloadData = lldpPacket.Bytes;

            return packet;

        }
コード例 #7
0
        public static List <NetworkInterfaceInfo> GetNetworkInterfaces()
        {
            var listNetworkInterfaceInfo = new List <NetworkInterfaceInfo>();

            foreach (var networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces())
            {
                // NetworkInterfaceType 53 is proprietary virtual/internal interface
                // https://docs.microsoft.com/en-us/windows-hardware/drivers/network/ndis-interface-types
                if (networkInterface.NetworkInterfaceType != NetworkInterfaceType.Ethernet && networkInterface.NetworkInterfaceType != NetworkInterfaceType.Wireless80211 && (int)networkInterface.NetworkInterfaceType != 53)
                {
                    continue;
                }

                var listIPv4Address          = new List <Tuple <IPAddress, IPAddress> >();
                var listIPv6AddressLinkLocal = new List <IPAddress>();
                var listIPv6Address          = new List <IPAddress>();

                var dhcpLeaseObtained = new DateTime();
                var dhcpLeaseExpires  = new DateTime();

                var ipProperties = networkInterface.GetIPProperties();

                foreach (var unicastIPAddrInfo in ipProperties.UnicastAddresses)
                {
                    switch (unicastIPAddrInfo.Address.AddressFamily)
                    {
                    case AddressFamily.InterNetwork:

                        listIPv4Address.Add(new Tuple <IPAddress, IPAddress>(unicastIPAddrInfo.Address, unicastIPAddrInfo.IPv4Mask));
                        dhcpLeaseExpires  = (DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressPreferredLifetime)).ToLocalTime();
                        dhcpLeaseObtained = (DateTime.UtcNow + TimeSpan.FromSeconds(unicastIPAddrInfo.AddressValidLifetime) - TimeSpan.FromSeconds(unicastIPAddrInfo.DhcpLeaseLifetime)).ToLocalTime();
                        break;

                    case AddressFamily.InterNetworkV6 when unicastIPAddrInfo.Address.IsIPv6LinkLocal:
                        listIPv6AddressLinkLocal.Add(unicastIPAddrInfo.Address);
                        break;

                    case AddressFamily.InterNetworkV6:
                        listIPv6Address.Add(unicastIPAddrInfo.Address);
                        break;
                    }
                }

                var listIPv4Gateway = new List <IPAddress>();
                var listIPv6Gateway = new List <IPAddress>();

                foreach (var gatewayIPAddrInfo in ipProperties.GatewayAddresses)
                {
                    switch (gatewayIPAddrInfo.Address.AddressFamily)
                    {
                    case AddressFamily.InterNetwork:
                        listIPv4Gateway.Add(gatewayIPAddrInfo.Address);
                        break;

                    case AddressFamily.InterNetworkV6:
                        listIPv6Gateway.Add(gatewayIPAddrInfo.Address);
                        break;
                    }
                }

                var listDhcpServer = new List <IPAddress>();

                foreach (var dhcpServerIPAddress in ipProperties.DhcpServerAddresses)
                {
                    if (dhcpServerIPAddress.AddressFamily == AddressFamily.InterNetwork)
                    {
                        listDhcpServer.Add(dhcpServerIPAddress);
                    }
                }

                // Check if autoconfiguration for DNS is enabled (only via registry key)
                var nameServerKey = Registry.LocalMachine.OpenSubKey($@"SYSTEM\CurrentControlSet\Services\Tcpip\Parameters\Interfaces\{networkInterface.Id}");
                var dnsAutoconfigurationEnabled = nameServerKey?.GetValue("NameServer") != null && string.IsNullOrEmpty(nameServerKey.GetValue("NameServer").ToString());

                var listDNSServer = new List <IPAddress>();

                foreach (var dnsServerIPAddress in ipProperties.DnsAddresses)
                {
                    listDNSServer.Add(dnsServerIPAddress);
                }

                // Check if IPv4 protocol is available
                var ipv4ProtocolAvailable = true;
                IPv4InterfaceProperties ipv4Properties = null;

                try
                {
                    ipv4Properties = ipProperties.GetIPv4Properties();
                }
                catch (NetworkInformationException)
                {
                    ipv4ProtocolAvailable = false;
                }

                // Check if IPv6 protocol is available
                var ipv6ProtocolAvailable = true;
                IPv6InterfaceProperties ipv6Properties = null;

                try
                {
                    ipv6Properties = ipProperties.GetIPv6Properties();
                }
                catch (NetworkInformationException)
                {
                    ipv6ProtocolAvailable = false;
                }

                listNetworkInterfaceInfo.Add(new NetworkInterfaceInfo
                {
                    Id                          = networkInterface.Id,
                    Name                        = networkInterface.Name,
                    Description                 = networkInterface.Description,
                    Type                        = networkInterface.NetworkInterfaceType.ToString(),
                    PhysicalAddress             = networkInterface.GetPhysicalAddress(),
                    Status                      = networkInterface.OperationalStatus,
                    IsOperational               = networkInterface.OperationalStatus == OperationalStatus.Up,
                    Speed                       = networkInterface.Speed,
                    IPv4ProtocolAvailable       = ipv4ProtocolAvailable,
                    IPv4Address                 = listIPv4Address.ToArray(),
                    IPv4Gateway                 = listIPv4Gateway.ToArray(),
                    DhcpEnabled                 = ipv4Properties != null && ipv4Properties.IsDhcpEnabled,
                    DhcpServer                  = listDhcpServer.ToArray(),
                    DhcpLeaseObtained           = dhcpLeaseObtained,
                    DhcpLeaseExpires            = dhcpLeaseExpires,
                    IPv6ProtocolAvailable       = ipv6ProtocolAvailable,
                    IPv6AddressLinkLocal        = listIPv6AddressLinkLocal.ToArray(),
                    IPv6Address                 = listIPv6Address.ToArray(),
                    IPv6Gateway                 = listIPv6Gateway.ToArray(),
                    DNSAutoconfigurationEnabled = dnsAutoconfigurationEnabled,
                    DNSSuffix                   = ipProperties.DnsSuffix,
                    DNSServer                   = listDNSServer.ToArray()
                });
            }

            return(listNetworkInterfaceInfo);
        }
コード例 #8
0
ファイル: UDPChannel.cs プロジェクト: RLwang14/Master-Thesis
        private void StartMulticastSocket(SocketSet info)
        {
            if (info._localEP.Address.IsIPv6Multicast)
            {
                try {
                    info._socket = SetupUDPSocket(AddressFamily.InterNetworkV6, ReceivePacketSize + 1);
                    info._socket.Socket.Bind(new IPEndPoint(IPAddress.IPv6Any, _port));

                    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
                    foreach (NetworkInterface adapter in nics)
                    {
                        if (!adapter.SupportsMulticast)
                        {
                            continue;
                        }
                        if (adapter.OperationalStatus != OperationalStatus.Up)
                        {
                            continue;
                        }
                        if (adapter.Supports(NetworkInterfaceComponent.IPv6))
                        {
                            IPInterfaceProperties properties = adapter.GetIPProperties();

                            foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses)
                            {
                                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                                {
                                    IPv6InterfaceProperties v6ip = adapter.GetIPProperties().GetIPv6Properties();
                                    IPv6MulticastOption     mc   = new IPv6MulticastOption(info._localEP.Address, v6ip.Index);
                                    try {
                                        info._socket.Socket.SetSocketOption(SocketOptionLevel.IPv6,
                                                                            SocketOptionName.AddMembership,
                                                                            mc);
                                    }
                                    catch (SocketException e) {
#if LOG_UDP_CHANNEL
                                        _Log.Info(
                                            m => m(
                                                $"Start Multicast:  Address {info._localEP.Address} had an exception ${e.ToString()}"));
#endif
                                    }

                                    break;
                                }
                            }
                        }
                    }
                }
                catch (SocketException e) {
#if LOG_UDP_CHANNEL
                    _Log.Info(
                        m => m($"Start Multicast:  Address {info._localEP.Address} had an exception ${e.ToString()}"));
                    throw;
#endif
                }
            }
            else
            {
                try {
                    info._socket = SetupUDPSocket(AddressFamily.InterNetwork, ReceivePacketSize + 1);
                    info._socket.Socket.Bind(new IPEndPoint(IPAddress.Any, _port));

                    NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();


                    foreach (NetworkInterface adapter in nics)
                    {
                        if (!adapter.SupportsMulticast)
                        {
                            continue;
                        }
                        if (adapter.OperationalStatus != OperationalStatus.Up)
                        {
                            continue;
                        }
                        if (adapter.Supports(NetworkInterfaceComponent.IPv4))
                        {
                            IPInterfaceProperties properties = adapter.GetIPProperties();

                            foreach (UnicastIPAddressInformation ip in adapter.GetIPProperties().UnicastAddresses)
                            {
                                if (ip.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                                {
                                    MulticastOption mc = new MulticastOption(info._localEP.Address, ip.Address);
                                    info._socket.Socket.SetSocketOption(SocketOptionLevel.IP,
                                                                        SocketOptionName.AddMembership,
                                                                        mc);
                                }
                            }
                        }
                    }
                }
                catch (SocketException e) {
#if LOG_UDP_CHANNEL
                    _Log.Info(m => m($"Start Multicast:  Address {info._localEP.Address} had an exception ${e.ToString()}"));
#endif
                    throw;
                }
            }


            if (ReceiveBufferSize > 0)
            {
                info._socket.Socket.ReceiveBufferSize = ReceiveBufferSize;
                if (info._socketBackup != null)
                {
                    info._socketBackup.Socket.ReceiveBufferSize = ReceiveBufferSize;
                }
            }

            if (SendBufferSize > 0)
            {
                info._socket.Socket.SendBufferSize = SendBufferSize;
                if (info._socketBackup != null)
                {
                    info._socketBackup.Socket.SendBufferSize = SendBufferSize;
                }
            }

            BeginReceive(info);
        }