[PlatformSpecific(PlatformID.Windows)] // Linux and OSX do not support some of these public void IPInfoTest_AccessAllIPv6Properties_NoErrors() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("IPv6 Properties:"); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { var nie = Assert.Throws <NetworkInformationException>(() => ipProperties.GetIPv6Properties()); Assert.Equal(SocketError.ProtocolNotSupported, (SocketError)nie.ErrorCode); continue; } IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); if (ipv6Properties == null) { _log.WriteLine("IPv6Properties is null"); continue; } _log.WriteLine("Index: " + ipv6Properties.Index); _log.WriteLine("Mtu: " + ipv6Properties.Mtu); _log.WriteLine("ScopeID: " + ipv6Properties.GetScopeId(ScopeLevel.Link)); } }
void FindNetworkInterfaces() { var nics = NetworkInterface.GetAllNetworkInterfaces() .Where(nic => nic.OperationalStatus == OperationalStatus.Up) .Where(nic => nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) .Where(nic => nic.SupportsMulticast) .Where(nic => !knownNics.Any(k => k.Id == nic.Id)) .ToArray(); foreach (var nic in nics) { lock (socketLock) { if (socket == null) { return; } IPInterfaceProperties properties = nic.GetIPProperties(); if (ip6) { var interfaceIndex = properties.GetIPv6Properties().Index; var mopt = new IPv6MulticastOption(MulticastAddressIp6, interfaceIndex); socket.SetSocketOption( SocketOptionLevel.IPv6, SocketOptionName.AddMembership, mopt); maxPacketSize = Math.Min(maxPacketSize, properties.GetIPv6Properties().Mtu - packetOverhead); } else { var interfaceIndex = properties.GetIPv4Properties().Index; var mopt = new MulticastOption(MulticastAddressIp4, interfaceIndex); socket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.AddMembership, mopt); maxPacketSize = Math.Min(maxPacketSize, properties.GetIPv4Properties().Mtu - packetOverhead); } knownNics.Add(nic); } } // Tell others. if (nics.Length > 0) { lock (socketLock) { if (socket == null) { return; } NetworkInterfaceDiscovered?.Invoke(this, new NetworkInterfaceEventArgs { NetworkInterfaces = nics }); } } }
[PlatformSpecific(PlatformID.Windows)] // Linux and OSX do not support GetScopeId public void IPv6ScopeId_AccessAllValues_Success() { Assert.True(Capability.IPv6Support()); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { continue; } IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("- IPv6 Scope levels:"); IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); Array values = Enum.GetValues(typeof(ScopeLevel)); foreach (ScopeLevel level in values) { _log.WriteLine("-- Level: " + level + "; " + ipv6Properties.GetScopeId(level)); } } }
static public List <IPInterfaceProperties> GetAllAddresses(AddressFamily addressFamily) { if (addressFamily != AddressFamily.InterNetwork && addressFamily != AddressFamily.InterNetworkV6) { throw new InvalidOperationException("AddressFamily either IPv4 or IPv6"); } List <IPInterfaceProperties> result = new List <IPInterfaceProperties>(); NetworkInterface[] ifs = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface netInterface in ifs) { IPInterfaceProperties ipProps = netInterface.GetIPProperties(); // if (netInterface.GetIPProperties().MulticastAddresses.Count == 0) // continue; // most of VPN adapters will be skipped if (!netInterface.SupportsMulticast) { continue; // multicast is meaningless for this type of connection } if (OperationalStatus.Up != netInterface.OperationalStatus) { continue; // this adapter is off or not connected } if ((addressFamily == AddressFamily.InterNetwork && ipProps.GetIPv4Properties() == null) || (addressFamily == AddressFamily.InterNetworkV6 && ipProps.GetIPv6Properties() == null)) { continue; // IPv4 is not configured on this adapter } result.Add(ipProps); } return(result); }
public async Task IPInfoTest_AccessAllIPv6Properties_NoErrors() { await Task.Run(() => { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("IPv6 Properties:"); IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); if (ipv6Properties == null) { _log.WriteLine("IPv6Properties is null"); continue; } _log.WriteLine("Index: " + ipv6Properties.Index); _log.WriteLine("Mtu: " + ipv6Properties.Mtu); _log.WriteLine("Scope: " + ipv6Properties.GetScopeId(ScopeLevel.Link)); } }).WaitAsync(TestHelper.PassingTestTimeout); }
private static NetworkInterface GetInterface(int index) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { try { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPv4InterfaceProperties ip4 = adapterProperties.GetIPv4Properties(); if ((ip4 != null) && (ip4.Index == index)) { return(adapter); } IPv6InterfaceProperties ip6 = adapterProperties.GetIPv6Properties(); if ((ip6 != null) && (ip6.Index == index)) { return(adapter); } } catch (NetworkInformationException e) { if (e.NativeErrorCode != (int)System.Net.Sockets.SocketError.ProtocolNotSupported) { throw; } } } return(null); }
public async Task IPv6ScopeId_AccessAllValues_Success() { await Task.Run(() => { Assert.True(Capability.IPv6Support()); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { continue; } IPInterfaceProperties ipProperties = nic.GetIPProperties(); IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); Array values = Enum.GetValues(typeof(ScopeLevel)); foreach (ScopeLevel level in values) { _log.WriteLine("-- Level: " + level + "; " + ipv6Properties.GetScopeId(level)); } } }).WaitAsync(TestHelper.PassingTestTimeout); }
/// <summary> /// Returns the index for the interface which has the ip address assigned /// </summary> /// <param name="ipAddress"> The ip address to look for </param> /// <returns> The index for the interface which has the ip address assigned </returns> public static int GetInterfaceIndex(this IPAddress ipAddress) { if (ipAddress == null) { throw new ArgumentNullException("ipAddress"); } IPInterfaceProperties interfaceProperty = NetworkInterface.GetAllNetworkInterfaces() .Select(n => n.GetIPProperties()) .FirstOrDefault(p => p.UnicastAddresses.Any(a => a.Address.Equals(ipAddress))); if (interfaceProperty != null) { if (ipAddress.AddressFamily == AddressFamily.InterNetwork) { IPv4InterfaceProperties property = interfaceProperty.GetIPv4Properties(); if (property != null) { return(property.Index); } } else { IPv6InterfaceProperties property = interfaceProperty.GetIPv6Properties(); if (property != null) { return(property.Index); } } } throw new ArgumentOutOfRangeException("ipAddress", "The given ip address is not configured on the local system"); }
private static IPv6InterfaceProperties GetIPv6Properties(IPInterfaceProperties props) { try { return(props.GetIPv6Properties()); } catch (NetworkInformationException) { return(null); } }
/// <summary> /// Bind a UDP client to each network adapter and set the index and address for multicast /// </summary> private void InitIPv6() { // Windows needs to have the IP Address and index set for an IPv6 multicast socket if (PlatformDetection.IsWindows) { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); List <UdpClient> clients = new List <UdpClient>(); foreach (var adapter in adapters) { if (adapter.OperationalStatus != OperationalStatus.Up) { continue; } if (adapter.Supports(NetworkInterfaceComponent.IPv6) && adapter.SupportsMulticast) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); if (adapterProperties == null) { continue; } UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; if (uniCast.Count > 0) { foreach (UnicastIPAddressInformation uni in uniCast) { if (uni.Address.AddressFamily != AddressFamily.InterNetworkV6) { continue; } //Only use LinkLocal or LocalHost addresses if (!uni.Address.IsIPv6LinkLocal && uni.Address != IPAddress.Parse("::1")) { continue; } clients.Add(NewClient(uni.Address, adapterProperties.GetIPv6Properties().Index)); } } } } } else { //Linux does not UdpClient client = NewClient(IPAddress.IPv6Any, 0); } }
IEnumerable <IPAddress> getIpv6Addr(NetworkInterface nic) { if (nic.Supports(NetworkInterfaceComponent.IPv6)) { IPInterfaceProperties ipprop = nic.GetIPProperties(); IPv6InterfaceProperties ipv6prop = ipprop.GetIPv6Properties(); foreach (UnicastIPAddressInformation addr in ipprop.UnicastAddresses) { if (addr.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6) { yield return(addr.Address); } } } }
//</Snippet48> //<Snippet49> public static void DisplayIPv6NetworkInterfaces() { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); Console.WriteLine("IPv6 interface information for {0}.{1}", properties.HostName, properties.DomainName); int count = 0; foreach (NetworkInterface adapter in nics) { // Only display informatin for interfaces that support IPv6. if (adapter.Supports(NetworkInterfaceComponent.IPv6) == false) { continue; } count++; Console.WriteLine(); Console.WriteLine(adapter.Description); // Underline the description. Console.WriteLine(String.Empty.PadLeft(adapter.Description.Length, '=')); IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); // Try to get the IPv6 interface properties. IPv6InterfaceProperties p = adapterProperties.GetIPv6Properties(); if (p == null) { Console.WriteLine("No IPv6 information is available for this interface."); Console.WriteLine(); continue; } // Display the IPv6 specific data. Console.WriteLine(" Index ............................. : {0}", p.Index); Console.WriteLine(" MTU ............................... : {0}", p.Mtu); } if (count == 0) { Console.WriteLine(" No IPv6 interfaces were found."); Console.WriteLine(); } }
[PlatformSpecific(PlatformID.Windows)] // Linux and OSX do not support GetScopeId public void IPv6ScopeId_GetLinkLevel_MatchesIndex() { Assert.True(Capability.IPv6Support()); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties ipProperties = nic.GetIPProperties(); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { continue; } IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); // This is not officially guaranteed by Windows, but it's what gets used. Assert.Equal(ipv6Properties.Index, ipv6Properties.GetScopeId(ScopeLevel.Link)); } }
/// <summary> /// Returns an appropriate NetworkInterface object for the specified interface index. /// </summary> /// <param name="interfaceIndex">The index of the interface for which to retrieve a NetworkInterface object.</param> public static NetworkInterface GetNetworkInterface(uint interfaceIndex) { foreach (NetworkInterface item in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties properties = item.GetIPProperties(); if (item.Supports(NetworkInterfaceComponent.IPv4) && properties.GetIPv4Properties().Index == interfaceIndex) { return(item); } if (item.Supports(NetworkInterfaceComponent.IPv6) && properties.GetIPv6Properties().Index == interfaceIndex) { return(item); } } throw new ArgumentOutOfRangeException(nameof(interfaceIndex)); }
private static string FormatNetworkInterface(NetworkInterface adapter) { string result = string.Empty; result += $"Interface: {adapter.Name}\n"; result += $" Description: {adapter.Description}\n"; result += $" ID: {adapter.Id}\n"; result += $" Type: {adapter.NetworkInterfaceType}\n"; result += $" Operational status: {adapter.OperationalStatus}\n"; result += $" Supports multicast: {adapter.SupportsMulticast}\n"; result += $" Physical address: {adapter.GetPhysicalAddress().ToString()}\n"; result += $" Supports IPv4: {adapter.Supports(NetworkInterfaceComponent.IPv4)}\n"; result += $" Supports IPv6: {adapter.Supports(NetworkInterfaceComponent.IPv6)}\n"; try { result += $" Receive only: {adapter.IsReceiveOnly}\n"; result += $" Speed: {adapter.Speed}\n"; } catch (PlatformNotSupportedException) { } if (adapter.NetworkInterfaceType != NetworkInterfaceType.Loopback) { IPInterfaceProperties properties = adapter.GetIPProperties(); result += FormatIPInterfaceProperties(properties); result += FormatIPInterfaceStatistics(adapter.GetIPStatistics()); if (adapter.Supports(NetworkInterfaceComponent.IPv4)) { result += FormatIPv4InterfaceProperties(properties.GetIPv4Properties()); result += FormatIPv4InterfaceStatistics(adapter.GetIPv4Statistics()); } if (adapter.Supports(NetworkInterfaceComponent.IPv6)) { result += FormatIPv6InterfaceProperties(properties.GetIPv6Properties()); } } return(result); }
public void Execute(ITerminal terminal) { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); IPGlobalProperties properties = IPGlobalProperties.GetIPGlobalProperties(); terminal.WriteLine($"IP interface information for {properties?.HostName}.{properties?.HostName}"); terminal.WriteLine(); foreach (NetworkInterface adapter in nics) { terminal.WriteLine(adapter.Description); if (adapter.Supports(NetworkInterfaceComponent.IPv4)) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); if (p == null) { terminal.WriteLine("No IPv4 information is available for this interface."); } else { terminal.WriteLine($" IPv4 MTU ............................... : {p.Mtu}"); } } if (adapter.Supports(NetworkInterfaceComponent.IPv6)) { IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); IPv6InterfaceProperties p = adapterProperties.GetIPv6Properties(); if (p == null) { terminal.WriteLine("No IPv6 information is available for this interface."); } else { terminal.WriteLine($" IPv6 MTU ............................... : {p.Mtu}"); } } } }
public async Task IPv6ScopeId_GetLinkLevel_MatchesIndex() { await Task.Run(() => { Assert.True(Capability.IPv6Support()); foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { IPInterfaceProperties ipProperties = nic.GetIPProperties(); if (!nic.Supports(NetworkInterfaceComponent.IPv6)) { continue; } IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); // This is not officially guaranteed by Windows, but it's what gets used. Assert.Equal(ipv6Properties.Index, ipv6Properties.GetScopeId(ScopeLevel.Link)); } }).WaitAsync(TestHelper.PassingTestTimeout); }
public static bool TryGetLoopbackInterfaceIndex(NetworkInterface adapter, bool ipv4, out int interfaceIndex) { Fx.Assert(adapter != null, "adapter can't be null"); Fx.Assert(adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback, "adapter type must be loopback adapter"); interfaceIndex = -1; bool result = false; if (ipv4 && adapter.Supports(NetworkInterfaceComponent.IPv4)) { interfaceIndex = NetworkInterface.LoopbackInterfaceIndex; result = true; } else if (!ipv4 && adapter.Supports(NetworkInterfaceComponent.IPv6)) { IPInterfaceProperties properties = adapter.GetIPProperties(); IPv6InterfaceProperties ipv6Properties = properties.GetIPv6Properties(); interfaceIndex = ipv6Properties.Index; result = true; } return(result); }
private static long GetInterfaceIndexFromIPAddress(IPAddress ipAddress) { foreach (NetworkInterface networkInterface in System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()) { if (networkInterface.Supports(NetworkInterfaceComponent.IPv6)) { IPInterfaceProperties ipProperties = networkInterface.GetIPProperties(); if (ipProperties != null) { foreach (UnicastIPAddressInformation address in ipProperties.UnicastAddresses) { if (address.Address?.ToString() == ipAddress.ToString()) { IPv6InterfaceProperties ipv6Properties = ipProperties?.GetIPv6Properties(); return(ipv6Properties?.Index ?? -1); } } } } } return(-1); }
public void IPInfoTest_AccessAllIPv6Properties_NoErrors() { foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces()) { _log.WriteLine("Nic: " + nic.Name); IPInterfaceProperties ipProperties = nic.GetIPProperties(); _log.WriteLine("IPv6 Properties:"); IPv6InterfaceProperties ipv6Properties = ipProperties.GetIPv6Properties(); if (ipv6Properties == null) { _log.WriteLine("IPv6Properties is null"); continue; } _log.WriteLine("Index: " + ipv6Properties.Index); _log.WriteLine("Mtu: " + ipv6Properties.Mtu); Assert.Throws <PlatformNotSupportedException>(() => ipv6Properties.GetScopeId(ScopeLevel.Link)); } }
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 + "'"); }
void InitSockets(bool updateListenPort) { bool ipV4; bool ipV6; UdpUtility.CheckSocketSupport(out ipV4, out ipV6); Fx.Assert(this.listenSockets == null, "listen sockets should only be initialized once"); this.listenSockets = new List <UdpSocket>(); int port = (this.listenUri.IsDefaultPort ? 0 : this.listenUri.Port); if (this.listenUri.HostNameType == UriHostNameType.IPv6 || this.listenUri.HostNameType == UriHostNameType.IPv4) { UdpUtility.ThrowOnUnsupportedHostNameType(this.listenUri); IPAddress address = IPAddress.Parse(this.listenUri.DnsSafeHost); if (UdpUtility.IsMulticastAddress(address)) { this.isMulticast = true; NetworkInterface[] adapters = UdpUtility.GetMulticastInterfaces(udpTransportBindingElement.MulticastInterfaceId); //if listening on a specific adapter, don't disable multicast loopback on that adapter. bool allowMulticastLoopback = !string.IsNullOrEmpty(this.udpTransportBindingElement.MulticastInterfaceId); for (int i = 0; i < adapters.Length; i++) { if (adapters[i].OperationalStatus == OperationalStatus.Up) { IPInterfaceProperties properties = adapters[i].GetIPProperties(); bool isLoopbackAdapter = adapters[i].NetworkInterfaceType == NetworkInterfaceType.Loopback; if (isLoopbackAdapter) { int interfaceIndex; if (UdpUtility.TryGetLoopbackInterfaceIndex(adapters[i], address.AddressFamily == AddressFamily.InterNetwork, out interfaceIndex)) { listenSockets.Add(UdpUtility.CreateListenSocket(address, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive, interfaceIndex, allowMulticastLoopback, isLoopbackAdapter)); } } else if (this.listenUri.HostNameType == UriHostNameType.IPv6) { if (adapters[i].Supports(NetworkInterfaceComponent.IPv6)) { IPv6InterfaceProperties v6Properties = properties.GetIPv6Properties(); if (v6Properties != null) { listenSockets.Add(UdpUtility.CreateListenSocket(address, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive, v6Properties.Index, allowMulticastLoopback, isLoopbackAdapter)); } } } else { if (adapters[i].Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceProperties v4Properties = properties.GetIPv4Properties(); if (v4Properties != null) { listenSockets.Add(UdpUtility.CreateListenSocket(address, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive, v4Properties.Index, allowMulticastLoopback, isLoopbackAdapter)); } } } } } if (listenSockets.Count == 0) { throw FxTrace.Exception.AsError(new ArgumentException(SR.UdpFailedToFindMulticastAdapter(this.listenUri))); } } else { //unicast - only sends on the default adapter... this.listenSockets.Add(UdpUtility.CreateUnicastListenSocket(address, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive)); } } else { IPAddress v4Address = IPAddress.Any; IPAddress v6Address = IPAddress.IPv6Any; if (ipV4 && ipV6) { if (port == 0) { //port 0 is only allowed when ListenUriMode == ListenUriMode.Unique UdpSocket ipv4Socket, ipv6Socket; port = UdpUtility.CreateListenSocketsOnUniquePort(v4Address, v6Address, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive, out ipv4Socket, out ipv6Socket); this.listenSockets.Add(ipv4Socket); this.listenSockets.Add(ipv6Socket); } else { this.listenSockets.Add(UdpUtility.CreateUnicastListenSocket(v4Address, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive)); this.listenSockets.Add(UdpUtility.CreateUnicastListenSocket(v6Address, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive)); } } else if (ipV4) { this.listenSockets.Add(UdpUtility.CreateUnicastListenSocket(v4Address, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive)); } else if (ipV6) { this.listenSockets.Add(UdpUtility.CreateUnicastListenSocket(v6Address, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive)); } } if (updateListenPort && port != this.listenUri.Port) { UriBuilder uriBuilder = new UriBuilder(this.listenUri); uriBuilder.Port = port; this.listenUri = uriBuilder.Uri; } // Open all the sockets to keep ref counts consistent foreach (UdpSocket udpSocket in this.ListenSockets) { udpSocket.Open(); } }
/// <summary> /// Loads the interface configuration into a cache for quick access /// </summary> public static void LoadCache() { NetworkInterface[] arnic = NetworkInterface.GetAllNetworkInterfaces(); bChacheLoaded = true; List <IPAddress[]> lipaAddresses = new List <IPAddress[]>(); List <IPAddress> lLocalIPAddresses = new List <IPAddress>(); List <string> lstrInterfaceNames = new List <string>(); List <MACAddress> lmcMacAddress = new List <MACAddress>(); List <Subnetmask[]> lsmSubnetmask = new List <Subnetmask[]>(); List <IPAddress[]> lipaStandardgateway = new List <IPAddress[]>(); List <bool> lbIPEnabled = new List <bool>(); List <string> lsterDNSHostname = new List <string>(); List <NetworkInterfaceType> lNicType = new List <NetworkInterfaceType>(); List <string> lEasyName = new List <string>(); List <string> lDescription = new List <string>(); List <int> lMTU = new List <int>(); dictNameIndex = new Dictionary <string, int>(); dictIntIndexStoreIndex = new Dictionary <int, int>(); int iStoreIndex = 0; foreach (NetworkInterface nic in arnic) { List <IPAddress> lipAddress = new List <IPAddress>(); List <Subnetmask> lsmMask = new List <Subnetmask>(); IPInterfaceProperties ipProps = nic.GetIPProperties(); IPv4InterfaceProperties ipv4Props = null; IPv6InterfaceProperties ipv6Props = null; try { ipv4Props = ipProps.GetIPv4Properties(); } catch { /*Black hole, since there is an exception if the protocol is not supported by the OS.*/ } try { ipv6Props = ipProps.GetIPv6Properties(); } catch { /*Black hole, since there is an exception if the protocol is not supported by the OS.*/ } //Skip interface if not IP ready if (ipProps != null && (ipv4Props != null || ipv6Props != null)) { int iIndex; if (ipv4Props != null) { iIndex = ipv4Props.Index; } else { iIndex = ipv6Props.Index; } dictIntIndexStoreIndex.Add(iIndex, iStoreIndex); //Get Name string strIntName = nic.Id; lstrInterfaceNames.Add(strIntName); dictNameIndex.Add(strIntName, iIndex); //Get IPS & Subnetmasks UnicastIPAddressInformationCollection aripTemp = ipProps.UnicastAddresses; for (int iC1 = 0; iC1 < aripTemp.Count; iC1++) { if (aripTemp[iC1].Address.AddressFamily == AddressFamily.InterNetwork || aripTemp[iC1].Address.AddressFamily == AddressFamily.InterNetworkV6) { if (aripTemp[iC1].IPv4Mask != null && aripTemp[iC1].Address != null && aripTemp[iC1].Address.AddressFamily == AddressFamily.InterNetwork) { lipAddress.Add(aripTemp[iC1].Address); lsmMask.Add(new Subnetmask(aripTemp[iC1].IPv4Mask.GetAddressBytes())); } else if (aripTemp[iC1].Address != null && aripTemp[iC1].Address.AddressFamily == AddressFamily.InterNetworkV6) { lipAddress.Add(aripTemp[iC1].Address); lsmMask.Add(Subnetmask.IPv6Default); } } } lipaAddresses.Add(lipAddress.ToArray()); lLocalIPAddresses.AddRange(lipAddress); lsmSubnetmask.Add(lsmMask.ToArray()); if (ipv4Props != null) { lMTU.Add(ipv4Props.Mtu); } else { lMTU.Add(ipv6Props.Mtu); } lipAddress.Clear(); lsmMask.Clear(); byte[] bAddressBytes = nic.GetPhysicalAddress().GetAddressBytes(); if (bAddressBytes.Length == 6) { lmcMacAddress.Add(new MACAddress(bAddressBytes)); } else { lmcMacAddress.Add(MACAddress.Empty); } //Get Standardgateways GatewayIPAddressInformationCollection arGateways = ipProps.GatewayAddresses; for (int iC1 = 0; iC1 < arGateways.Count; iC1++) { IPAddress ipa = arGateways[iC1].Address; if (ipa.AddressFamily == AddressFamily.InterNetwork || ipa.AddressFamily == AddressFamily.InterNetworkV6) { lipAddress.Add(ipa); } } lipaStandardgateway.Add(lipAddress.ToArray()); lDescription.Add(nic.Description); lEasyName.Add(nic.Name); lNicType.Add(nic.NetworkInterfaceType); iStoreIndex++; } } arInterfaceNames = lstrInterfaceNames.ToArray(); arIPAddresses = lipaAddresses.ToArray(); arMACAddresses = lmcMacAddress.ToArray(); arSubnetmasks = lsmSubnetmask.ToArray(); arStandardgateways = lipaStandardgateway.ToArray(); arIPEnabled = lbIPEnabled.ToArray(); arLocalIPAddresses = lLocalIPAddresses.ToArray(); arAdapterType = lNicType.ToArray(); arDescription = lDescription.ToArray(); arEasyName = lEasyName.ToArray(); arMTU = lMTU.ToArray(); }
/// <summary> /// Obtains information about network interfaces. Formats and returns it /// similar to "ipconfig" command. /// </summary> public static string GetNetworkInformation(Boolean activeOnly) { string title; StringBuilder info = new StringBuilder(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); if (nics == null || nics.Length < 1) { info.AppendLine("No network interfaces found."); return(info.ToString()); } title = String.Format("{0}Network Interfaces", activeOnly ? "Active " : ""); info.AppendLine(title); info.AppendLine(String.Empty.PadLeft(title.Length, '=')); foreach (NetworkInterface adapter in nics) { IPInterfaceProperties properties = adapter.GetIPProperties(); // continue to the next adapter if we are only showing active ones. if (activeOnly && adapter.OperationalStatus != OperationalStatus.Up) { continue; } info.AppendLine(); title = String.Format("{0} adapter {1}", adapter.NetworkInterfaceType, adapter.Name); info.AppendLine(title); info.AppendLine(String.Empty.PadLeft(title.Length, '-')); info.AppendFormat("Description . . . . . . . . . . . . . . . : {0}\n", adapter.Description); info.AppendFormat("Physical Address . . . . . . . . . . . . : {0}\n", adapter.GetPhysicalAddress()); info.AppendFormat("Operational status . . . . . . . . . . . : {0}\n", adapter.OperationalStatus); // The following information is not useful for loopback adapters. if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } // DNS info.AppendFormat("DNS Services . . . . . . . . . . . . . . : {0}\n", properties.IsDynamicDnsEnabled ? "dynamic" : properties.IsDnsEnabled ? "enabled" : "disabled"); if (!String.IsNullOrEmpty(properties.DnsSuffix)) { info.AppendFormat("DNS Suffix . . . . . . . . . . . . . . . : {0}\n", properties.DnsSuffix); } if (properties.DnsAddresses != null && properties.DnsAddresses.Count > 0) { AddIpAddresses(info, "DNS Servers . . . . . . . . . . . . . . . : ", properties.DnsAddresses); } // IPv4 if (adapter.Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceProperties ipv4 = properties.GetIPv4Properties(); if (ipv4 != null) { if (ipv4.UsesWins) { IPAddressCollection winsServers = properties.WinsServersAddresses; if (winsServers != null && winsServers.Count > 0) { AddIpAddresses(info, "WINS Servers . . . . . . . . . . . . . . : ", winsServers); } } info.AppendFormat("IPv4 DHCP Enabled . . . . . . . . . . . . : {0}\n", ipv4.IsDhcpEnabled); info.AppendFormat("IPv4 MTU . . . . . . . . . . . . . . . . : {0}\n", ipv4.Mtu); } } // IPv6 if (adapter.Supports(NetworkInterfaceComponent.IPv6)) { IPv6InterfaceProperties ipv6 = properties.GetIPv6Properties(); if (ipv6 != null) { info.AppendFormat("IPv6 MTU . . . . . . . . . . . . . . . . : {0}\n", ipv6.Mtu); info.AppendFormat("IPv6 Interface Index . . . . . . . . . . : {0}\n", ipv6.Index); } } info.AppendFormat("Speed . . . . . . . . . . . . . . . . . . : {0} MBps\n", adapter.Speed / 1000000); info.AppendFormat("Receive Only . . . . . . . . . . . . . . : {0}\n", adapter.IsReceiveOnly); info.AppendFormat("Multicast . . . . . . . . . . . . . . . . : {0}\n", adapter.SupportsMulticast); } return(info.ToString()); }
/// <inheritdoc /> public IIPv6InterfaceProperties GetIPv6Properties() { return(_props.GetIPv6Properties().ToInterface()); }
private static IPv6InterfaceProperties GetIPv6Properties(IPInterfaceProperties props) { try { return props.GetIPv6Properties(); } catch (NetworkInformationException) { return null; } }
public void AdapterDetails() { NetworkInterface nic = nicArr[cbNetworkChoices.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) { listBoxDetails.Items.Add(a); } }
//will only return > 1 socket when both of the following are true: // 1) multicast // 2) sending on all interfaces UdpSocket[] GetSockets(Uri via, out IPEndPoint remoteEndPoint, out bool isMulticast) { UdpSocket[] results = null; remoteEndPoint = null; IPAddress[] remoteAddressList; isMulticast = false; UdpUtility.ThrowIfNoSocketSupport(); if (via.HostNameType == UriHostNameType.IPv6 || via.HostNameType == UriHostNameType.IPv4) { UdpUtility.ThrowOnUnsupportedHostNameType(via); IPAddress address = IPAddress.Parse(via.DnsSafeHost); isMulticast = UdpUtility.IsMulticastAddress(address); remoteAddressList = new IPAddress[] { address }; } else { remoteAddressList = DnsCache.Resolve(via).AddressList; } if (remoteAddressList.Length < 1) { // System.Net.Dns shouldn't ever allow this to happen, but... Fx.Assert("DnsCache returned a HostEntry with zero length address list"); throw FxTrace.Exception.AsError(new EndpointNotFoundException(SR.DnsResolveFailed(via.DnsSafeHost))); } remoteEndPoint = new IPEndPoint(remoteAddressList[0], via.Port); IPAddress localAddress; if (via.IsLoopback) { localAddress = (remoteEndPoint.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Loopback : IPAddress.IPv6Loopback); } else { localAddress = (remoteEndPoint.AddressFamily == AddressFamily.InterNetwork ? IPAddress.Any : IPAddress.IPv6Any); } int port = 0; if (isMulticast) { List <UdpSocket> socketList = new List <UdpSocket>(); NetworkInterface[] adapters = UdpUtility.GetMulticastInterfaces(this.udpTransportBindingElement.MulticastInterfaceId); //if listening on a specific adapter, don't disable multicast loopback on that adapter. bool allowMulticastLoopback = !string.IsNullOrEmpty(this.udpTransportBindingElement.MulticastInterfaceId); for (int i = 0; i < adapters.Length; i++) { if (adapters[i].OperationalStatus == OperationalStatus.Up) { IPInterfaceProperties properties = adapters[i].GetIPProperties(); bool isLoopbackAdapter = adapters[i].NetworkInterfaceType == NetworkInterfaceType.Loopback; if (isLoopbackAdapter) { int interfaceIndex; if (UdpUtility.TryGetLoopbackInterfaceIndex(adapters[i], localAddress.AddressFamily == AddressFamily.InterNetwork, out interfaceIndex)) { socketList.Add(UdpUtility.CreateListenSocket(localAddress, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive, interfaceIndex, allowMulticastLoopback, isLoopbackAdapter)); } } else if (localAddress.AddressFamily == AddressFamily.InterNetworkV6) { if (adapters[i].Supports(NetworkInterfaceComponent.IPv6)) { IPv6InterfaceProperties v6Properties = properties.GetIPv6Properties(); if (v6Properties != null) { socketList.Add(UdpUtility.CreateListenSocket(localAddress, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive, v6Properties.Index, allowMulticastLoopback, isLoopbackAdapter)); } } } else { if (adapters[i].Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceProperties v4Properties = properties.GetIPv4Properties(); if (v4Properties != null) { socketList.Add(UdpUtility.CreateListenSocket(localAddress, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive, v4Properties.Index, allowMulticastLoopback, isLoopbackAdapter)); } } } } //CreateListenSocket sets the port, but since we aren't listening //on multicast, each socket can't share the same port. port = 0; } if (socketList.Count == 0) { throw FxTrace.Exception.AsError(new ArgumentException(SR.UdpFailedToFindMulticastAdapter(via))); } results = socketList.ToArray(); } else { UdpSocket socket = UdpUtility.CreateUnicastListenSocket(localAddress, ref port, this.udpTransportBindingElement.SocketReceiveBufferSize, this.udpTransportBindingElement.TimeToLive); results = new UdpSocket[] { socket }; } Fx.Assert(results != null, "GetSockets(...) return results should never be null. An exception should have been thrown but wasn't."); return(results); }
/// <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); string sysname = ""; sysname = String.Format("{0}:{1}", Environment.MachineName, GetServiceTag()); // 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( sysname )); 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; }
private string GetDeviceInfo(NetworkInterface adapter) { if (adapter == null) { return(String.Empty); } IPInterfaceProperties properties = adapter.GetIPProperties(); StringBuilder infoBuilder = new StringBuilder(); infoBuilder.Append(adapter.Description + "\n"); infoBuilder.Append("=================================================\n"); infoBuilder.AppendFormat(" ID ......................... : {0}\n", adapter.Id); infoBuilder.AppendFormat(" Name ....................... : {0}\n", adapter.Name); infoBuilder.AppendFormat(" Interface type ............. : {0}\n", adapter.NetworkInterfaceType); infoBuilder.AppendFormat(" Physical Address ........... : {0}\n", BitConverter.ToString(adapter.GetPhysicalAddress().GetAddressBytes())); infoBuilder.AppendFormat(" Operational status ......... : {0}\n", adapter.OperationalStatus); infoBuilder.AppendFormat(" Speed ...................... : {0} Mb/s\n", adapter.Speed / 1000000); string versions = String.Empty; // Create a display string for the supported IP versions. if (adapter.Supports(NetworkInterfaceComponent.IPv4)) { versions = "IPv4"; } if (adapter.Supports(NetworkInterfaceComponent.IPv6)) { if (versions.Length > 0) { versions += " "; } versions += "IPv6"; } infoBuilder.AppendFormat(" IP version ................. : {0}\n", versions); infoBuilder.Append(GetIPAddresses(properties)); // The following information is not useful for loopback adapters. if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) { return(infoBuilder.ToString()); } infoBuilder.AppendFormat(" DNS suffix ................. : {0}\n", properties.DnsSuffix); if (adapter.Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceProperties ipv4 = properties.GetIPv4Properties(); infoBuilder.AppendFormat(" Index ...................... : {0}\n", ipv4.Index); infoBuilder.AppendFormat(" MTU ........................ : {0}\n", ipv4.Mtu); infoBuilder.AppendFormat(" APIPA active ............... : {0}\n", ipv4.IsAutomaticPrivateAddressingActive); infoBuilder.AppendFormat(" APIPA enabled .............. : {0}\n", ipv4.IsAutomaticPrivateAddressingEnabled); infoBuilder.AppendFormat(" DHCP enabled ............... : {0}\n", ipv4.IsDhcpEnabled); infoBuilder.AppendFormat(" Forwarding enabled.......... : {0}\n", ipv4.IsForwardingEnabled); infoBuilder.AppendFormat(" Uses WINS .................. : {0}\n", ipv4.UsesWins); if (ipv4.UsesWins) { IPAddressCollection winsServers = properties.WinsServersAddresses; if (winsServers.Count > 0) { foreach (IPAddress winsServer in winsServers) { infoBuilder.AppendFormat(" WINS Server ................ : {0}\n", winsServer); } } } } if (adapter.Supports(NetworkInterfaceComponent.IPv6)) { IPv6InterfaceProperties ipv6 = properties.GetIPv6Properties(); infoBuilder.AppendFormat(" Index ...................... : {0}\n", ipv6.Index); infoBuilder.AppendFormat(" MTU ........................ : {0}\n", ipv6.Mtu); } infoBuilder.AppendFormat(" DNS enabled ................ : {0}\n", properties.IsDnsEnabled); infoBuilder.AppendFormat(" Dynamically configured DNS . : {0}\n", properties.IsDynamicDnsEnabled); infoBuilder.AppendFormat(" Receive Only ............... : {0}\n", adapter.IsReceiveOnly); infoBuilder.AppendFormat(" Multicast .................. : {0}\n", adapter.SupportsMulticast); return(infoBuilder.ToString()); }
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}'"); }