// This constructor is for Vista and newer internal SystemIPInterfaceProperties(FixedInfo fixedInfo, IpAdapterAddresses ipAdapterAddresses) { adapterFlags = ipAdapterAddresses.flags; dnsSuffix = ipAdapterAddresses.dnsSuffix; dnsEnabled = fixedInfo.EnableDns; dynamicDnsEnabled = ((ipAdapterAddresses.flags & AdapterFlags.DnsEnabled) > 0); multicastAddresses = SystemMulticastIPAddressInformation.ToMulticastIpAddressInformationCollection( IpAdapterAddress.MarshalIpAddressInformationCollection(ipAdapterAddresses.firstMulticastAddress)); dnsAddresses = IpAdapterAddress.MarshalIpAddressCollection(ipAdapterAddresses.firstDnsServerAddress); anycastAddresses = IpAdapterAddress.MarshalIpAddressInformationCollection( ipAdapterAddresses.firstAnycastAddress); unicastAddresses = SystemUnicastIPAddressInformation.MarshalUnicastIpAddressInformationCollection( ipAdapterAddresses.firstUnicastAddress); winsServersAddresses = IpAdapterAddress.MarshalIpAddressCollection( ipAdapterAddresses.firstWinsServerAddress); gatewayAddresses = SystemGatewayIPAddressInformation.ToGatewayIpAddressInformationCollection( IpAdapterAddress.MarshalIpAddressCollection(ipAdapterAddresses.firstGatewayAddress)); dhcpServers = new IPAddressCollection(); if (ipAdapterAddresses.dhcpv4Server.address != IntPtr.Zero) dhcpServers.InternalAdd(ipAdapterAddresses.dhcpv4Server.MarshalIPAddress()); if (ipAdapterAddresses.dhcpv6Server.address != IntPtr.Zero) dhcpServers.InternalAdd(ipAdapterAddresses.dhcpv6Server.MarshalIPAddress()); if ((adapterFlags & AdapterFlags.IPv4Enabled) != 0) { ipv4Properties = new SystemIPv4InterfaceProperties(fixedInfo, ipAdapterAddresses); } if ((adapterFlags & AdapterFlags.IPv6Enabled) != 0) { ipv6Properties = new SystemIPv6InterfaceProperties(ipAdapterAddresses.ipv6Index, ipAdapterAddresses.mtu, ipAdapterAddresses.zoneIndices); } }
public unsafe override UnicastIPAddressInformationCollection GetUnicastAddresses() { UnicastIPAddressInformationCollection collection = new UnicastIPAddressInformationCollection(); Interop.Sys.EnumerateInterfaceAddresses( (name, ipAddressInfo, netmaskInfo) => { IPAddress ipAddress = IPAddressUtil.GetIPAddressFromNativeInfo(ipAddressInfo); if (!IPAddressUtil.IsMulticast(ipAddress)) { IPAddress netMaskAddress = IPAddressUtil.GetIPAddressFromNativeInfo(netmaskInfo); collection.InternalAdd(new UnixUnicastIPAddressInformation(ipAddress, netMaskAddress)); } }, (name, ipAddressInfo, scopeId) => { IPAddress ipAddress = IPAddressUtil.GetIPAddressFromNativeInfo(ipAddressInfo); if (!IPAddressUtil.IsMulticast(ipAddress)) { collection.InternalAdd(new UnixUnicastIPAddressInformation(ipAddress, IPAddress.Any)); } }, // Ignore link-layer addresses that are discovered; don't create a callback. null); return collection; }
internal SystemIPInterfaceProperties(FixedInfo fixedInfo, IpAdapterAddresses ipAdapterAddresses) { this.dnsEnabled = fixedInfo.EnableDns; this.index = ipAdapterAddresses.index; this.name = ipAdapterAddresses.AdapterName; this.ipv6Index = ipAdapterAddresses.ipv6Index; if (this.index > 0) { this.versionSupported |= IPVersion.IPv4; } if (this.ipv6Index > 0) { this.versionSupported |= IPVersion.IPv6; } this.mtu = ipAdapterAddresses.mtu; this.adapterFlags = ipAdapterAddresses.flags; this.dnsSuffix = ipAdapterAddresses.dnsSuffix; this.dynamicDnsEnabled = (ipAdapterAddresses.flags & AdapterFlags.DnsEnabled) > 0; this.multicastAddresses = SystemMulticastIPAddressInformation.ToAddressInformationCollection(ipAdapterAddresses.FirstMulticastAddress); this.dnsAddresses = SystemIPAddressInformation.ToAddressCollection(ipAdapterAddresses.FirstDnsServerAddress, this.versionSupported); this.anycastAddresses = SystemIPAddressInformation.ToAddressInformationCollection(ipAdapterAddresses.FirstAnycastAddress, this.versionSupported); this.unicastAddresses = SystemUnicastIPAddressInformation.ToAddressInformationCollection(ipAdapterAddresses.FirstUnicastAddress); if (this.ipv6Index > 0) { this.ipv6Properties = new SystemIPv6InterfaceProperties(this.ipv6Index, this.mtu); } }
private static UnicastIPAddressInformationCollection GetUnicastAddresses(UnixNetworkInterface uni) { var collection = new UnicastIPAddressInformationCollection(); foreach (IPAddress address in uni.Addresses.Where((addr) => !IsMulticast(addr))) { IPAddress netMask = (address.AddressFamily == AddressFamily.InterNetwork) ? uni.GetNetMaskForIPv4Address(address) : IPAddress.Any; // Windows compatibility collection.InternalAdd(new UnixUnicastIPAddressInformation(address, netMask)); } return collection; }
internal SystemIPInterfaceProperties(Interop.IpHlpApi.FIXED_INFO fixedInfo, Interop.IpHlpApi.IpAdapterAddresses ipAdapterAddresses) { _adapterFlags = ipAdapterAddresses.flags; _dnsSuffix = ipAdapterAddresses.dnsSuffix; _dnsEnabled = fixedInfo.enableDns; _dynamicDnsEnabled = ((ipAdapterAddresses.flags & Interop.IpHlpApi.AdapterFlags.DnsEnabled) > 0); _multicastAddresses = SystemMulticastIPAddressInformation.ToMulticastIpAddressInformationCollection( Interop.IpHlpApi.IpAdapterAddress.MarshalIpAddressInformationCollection(ipAdapterAddresses.firstMulticastAddress)); _dnsAddresses = Interop.IpHlpApi.IpAdapterAddress.MarshalIpAddressCollection(ipAdapterAddresses.firstDnsServerAddress); _anycastAddresses = Interop.IpHlpApi.IpAdapterAddress.MarshalIpAddressInformationCollection( ipAdapterAddresses.firstAnycastAddress); _unicastAddresses = SystemUnicastIPAddressInformation.MarshalUnicastIpAddressInformationCollection( ipAdapterAddresses.firstUnicastAddress); _winsServersAddresses = Interop.IpHlpApi.IpAdapterAddress.MarshalIpAddressCollection( ipAdapterAddresses.firstWinsServerAddress); _gatewayAddresses = SystemGatewayIPAddressInformation.ToGatewayIpAddressInformationCollection( Interop.IpHlpApi.IpAdapterAddress.MarshalIpAddressCollection(ipAdapterAddresses.firstGatewayAddress)); _dhcpServers = new InternalIPAddressCollection(); if (ipAdapterAddresses.dhcpv4Server.address != IntPtr.Zero) { _dhcpServers.InternalAdd(ipAdapterAddresses.dhcpv4Server.MarshalIPAddress()); } if (ipAdapterAddresses.dhcpv6Server.address != IntPtr.Zero) { _dhcpServers.InternalAdd(ipAdapterAddresses.dhcpv6Server.MarshalIPAddress()); } if ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv4Enabled) != 0) { _ipv4Properties = new SystemIPv4InterfaceProperties(fixedInfo, ipAdapterAddresses); } if ((_adapterFlags & Interop.IpHlpApi.AdapterFlags.IPv6Enabled) != 0) { _ipv6Properties = new SystemIPv6InterfaceProperties(ipAdapterAddresses.ipv6Index, ipAdapterAddresses.mtu, ipAdapterAddresses.zoneIndices); } }
internal static UnicastIPAddressInformationCollection ToAddressInformationCollection(IntPtr ptr) { UnicastIPAddressInformationCollection informations = new UnicastIPAddressInformationCollection(); if (ptr != IntPtr.Zero) { IPEndPoint point; IpAdapterUnicastAddress adapterAddress = (IpAdapterUnicastAddress) Marshal.PtrToStructure(ptr, typeof(IpAdapterUnicastAddress)); AddressFamily family = (adapterAddress.address.addressLength > 0x10) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; SocketAddress socketAddress = new SocketAddress(family, adapterAddress.address.addressLength); Marshal.Copy(adapterAddress.address.address, socketAddress.m_Buffer, 0, adapterAddress.address.addressLength); if (family == AddressFamily.InterNetwork) { point = (IPEndPoint) IPEndPoint.Any.Create(socketAddress); } else { point = (IPEndPoint) IPEndPoint.IPv6Any.Create(socketAddress); } informations.InternalAdd(new SystemUnicastIPAddressInformation(adapterAddress, point.Address)); while (adapterAddress.next != IntPtr.Zero) { adapterAddress = (IpAdapterUnicastAddress) Marshal.PtrToStructure(adapterAddress.next, typeof(IpAdapterUnicastAddress)); family = (adapterAddress.address.addressLength > 0x10) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork; socketAddress = new SocketAddress(family, adapterAddress.address.addressLength); Marshal.Copy(adapterAddress.address.address, socketAddress.m_Buffer, 0, adapterAddress.address.addressLength); if (family == AddressFamily.InterNetwork) { point = (IPEndPoint) IPEndPoint.Any.Create(socketAddress); } else { point = (IPEndPoint) IPEndPoint.IPv6Any.Create(socketAddress); } informations.InternalAdd(new SystemUnicastIPAddressInformation(adapterAddress, point.Address)); } } return informations; }
internal SystemIPInterfaceProperties(FixedInfo fixedInfo, IpAdapterInfo ipAdapterInfo) { this.dnsEnabled = fixedInfo.EnableDns; this.name = ipAdapterInfo.adapterName; this.index = ipAdapterInfo.index; this.multicastAddresses = new MulticastIPAddressInformationCollection(); this.anycastAddresses = new IPAddressInformationCollection(); if (this.index > 0) { this.versionSupported |= IPVersion.IPv4; } if (ComNetOS.IsWin2K) { this.ReadRegDnsSuffix(); } this.unicastAddresses = new UnicastIPAddressInformationCollection(); foreach (IPExtendedAddress address in ipAdapterInfo.ipAddressList.ToIPExtendedAddressArrayList()) { this.unicastAddresses.InternalAdd(new SystemUnicastIPAddressInformation(ipAdapterInfo, address)); } try { this.ipv4Properties = new SystemIPv4InterfaceProperties(fixedInfo, ipAdapterInfo); if ((this.dnsAddresses == null) || (this.dnsAddresses.Count == 0)) { this.dnsAddresses = this.ipv4Properties.DnsAddresses; } } catch (NetworkInformationException exception) { if (exception.ErrorCode != 0x57L) { throw; } } }
private void UpdateNetworkInterface() { if (ComboBox_Network_interface.Items.Count >= 1) // if the number of items are less greater than or equal to one { // Grab NetworkInterface object that describes the current interface NetworkInterface nic = nicArr[ComboBox_Network_interface.SelectedIndex]; IPInterfaceProperties properties = nic.GetIPProperties(); Object test = nic.Speed; // Grab the stats for that interface IPv4InterfaceStatistics interfaceStats = nic.GetIPv4Statistics(); //takes the bytes sent from the interface and put it in the text for the bytes sent amount text of the text block. String BytesSentAmountCastContent2; BytesSentAmountCastContent2 = (String)BytesSentAmountLabel.Content; long bytesSentSpeed = (long)(interfaceStats.BytesSent - double.Parse(BytesSentAmountCastContent2)) / 1000; //converts the bytes to a KiloBytes(kB). long SentSpeedToMegaBytes = bytesSentSpeed / 1000; // converts the sentspeed from kilobytes(KB) to MegaBytes(MB) // String BytesSentSpeedToDouble = Convert.ToDouble(by) //long whatever = ByteSentSpeedToObject - (bytesSentSpeed / 1024); BytesSentAmountLabel.Content = interfaceStats.BytesSent.ToString("N0"); // sets the label text to be equal to the bytes sent speed. String BytesReceivedAmountCast; BytesReceivedAmountCast = (String)BytesReceivedAmountLabel.Content; //takes the bytes received from the interface and put it in the text for the bytes received amount text of the text block. long bytesReceivedSpeed = (long)(interfaceStats.BytesReceived - double.Parse(BytesReceivedAmountCast)) / 1000; //String ByteRecievedToString = bytesReceivedSpeed.ToString("N0") + " KB/s"; // converts it to a string with commas separating it. BytesReceivedAmountLabel.Content = interfaceStats.BytesReceived.ToString("N0"); // Update the labels long SpeedAmountBytes = (long)(nic.Speed / 8000); String SpeedAmountBytesToString = SpeedAmountBytes.ToString("N0") + " KB/s"; SpeedAmountLabel.Content = SpeedAmountBytesToString; //Bytes_Received_amount_Textblock.Text = interfaceStats.BytesReceived.ToString("N0"); // Bytes_Sent_amount.Text = interfaceStats.BytesSent.ToString("N0"); UploadAmountLabel.Content = bytesSentSpeed.ToString() + " KB/s"; DownloadAmountLabel.Content = bytesReceivedSpeed.ToString() + " KB/s"; //gets the current date and time. DateTime now = DateTime.Now; String BytseSentSpeedString = bytesSentSpeed.ToString(); String DownloadString = bytesReceivedSpeed.ToString(); String DateTimeString = now.ToString("hh:mm"); UpdateList(DateTimeString, BytseSentSpeedString, DownloadString); //GenerateExcelFileandUpdate(BytseSentSpeedString, DownloadString); //add the current upload speed to the tuple. //var DataStuff = new List<Tuple<String, String, Object>> Tuple <String, String, Object> DataTuple = new Tuple <String, String, Object>(now.ToString(), "Upload", bytesSentSpeed.ToString()); //DataTuple. // get the IP address of the current selected network interface. UnicastIPAddressInformationCollection ipInfo = nic.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation item in ipInfo) { //if the IP address is in the system range of Ip addresses if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { IP_Address_Of_Computer.Content = item.Address.ToString(); // add the IP address to the text of IP address info text block. break; } } } }
public static void ShowIPAddresses(IPInterfaceProperties adapterProperties) // MSDN The following code example displays address information. MSDN - по идее этот метод для метода выше ShowNetworkInterfaces() { IPAddressCollection dnsServers = adapterProperties.DnsAddresses; if (dnsServers != null) { foreach (IPAddress dns in dnsServers) { Console.WriteLine(" DNS Servers ............................. : {0}", dns.ToString() ); } } IPAddressInformationCollection anyCast = adapterProperties.AnycastAddresses; if (anyCast != null) { foreach (IPAddressInformation any in anyCast) { Console.WriteLine(" Anycast Address .......................... : {0} {1} {2}", any.Address, any.IsTransient ? "Transient" : "", any.IsDnsEligible ? "DNS Eligible" : "" ); } Console.WriteLine(); } MulticastIPAddressInformationCollection multiCast = adapterProperties.MulticastAddresses; if (multiCast != null) { foreach (IPAddressInformation multi in multiCast) { Console.WriteLine(" Multicast Address ....................... : {0} {1} {2}", multi.Address, multi.IsTransient ? "Transient" : "", multi.IsDnsEligible ? "DNS Eligible" : "" ); } Console.WriteLine(); } UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; if (uniCast != null) { string lifeTimeFormat = "dddd, MMMM dd, yyyy hh:mm:ss tt"; foreach (UnicastIPAddressInformation uni in uniCast) { DateTime when; Console.WriteLine(" Unicast Address ......................... : {0}", uni.Address); Console.WriteLine(" Prefix Origin ........................ : {0}", uni.PrefixOrigin); Console.WriteLine(" Suffix Origin ........................ : {0}", uni.SuffixOrigin); Console.WriteLine(" Duplicate Address Detection .......... : {0}", uni.DuplicateAddressDetectionState); // Format the lifetimes as Sunday, February 16, 2003 11:33:44 PM // if en-us is the current culture. // Calculate the date and time at the end of the lifetimes. when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressValidLifetime); when = when.ToLocalTime(); Console.WriteLine(" Valid Life Time ...................... : {0}", when.ToString(lifeTimeFormat, System.Globalization.CultureInfo.CurrentCulture) ); when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressPreferredLifetime); when = when.ToLocalTime(); Console.WriteLine(" Preferred life time .................. : {0}", when.ToString(lifeTimeFormat, System.Globalization.CultureInfo.CurrentCulture) ); when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime); when = when.ToLocalTime(); Console.WriteLine(" DHCP Leased Life Time ................ : {0}", when.ToString(lifeTimeFormat, System.Globalization.CultureInfo.CurrentCulture) ); } Console.WriteLine(); } }
// ------------------------------------------------------------- // // Startup() - called when the plugin is loaded // // // todo: // // 1) probably add error checking on all 'new' operations // and system calls // // 2) better error reporting and logging // // 3) Sequence # should be per universe // // ------------------------------------------------------------- public override void Start() { bool cleanStart = true; base.Start(); if (!PluginInstances.Contains(this)) { PluginInstances.Add(this); } // working copy of networkinterface object NetworkInterface networkInterface; // a single socket to use for unicast (if needed) Socket unicastSocket = null; // working ipaddress object IPAddress ipAddress = null; // a sortedlist containing the multicast sockets we've already done var nicSockets = new SortedList <string, Socket>(); // load all of our xml into working objects this.LoadSetupNodeInfo(); // initialize plugin wide stats this._eventCnt = 0; this._totalTicks = 0; if (_data.Unicast == null && _data.Multicast == null) { if (_data.Universes[0] != null && (_data.Universes[0].Multicast != null || _data.Universes[0].Unicast != null)) { _data.Unicast = _data.Universes[0].Unicast; _data.Multicast = _data.Universes[0].Multicast; if (!_updateWarn) { //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible) MessageBoxForm.msgIcon = SystemIcons.Information; //this is used if you want to add a system icon to the message form. var messageBox = new MessageBoxForm( "The E1.31 plugin is importing data from an older version of the plugin. Please verify the new Streaming ACN (E1.31) configuration.", "Vixen 3 Streaming ACN (E1.31) plugin", false, false); messageBox.ShowDialog(); _updateWarn = true; } } } // find all of the network interfaces & build a sorted list indexed by Id this._nicTable = new SortedList <string, NetworkInterface>(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (var nic in nics) { if (nic.NetworkInterfaceType != NetworkInterfaceType.Tunnel && nic.NetworkInterfaceType != NetworkInterfaceType.Loopback) { this._nicTable.Add(nic.Id, nic); } } if (_data.Unicast != null) { if (!unicasts.ContainsKey(_data.Unicast)) { unicasts.Add(_data.Unicast, 0); } } // initialize messageTexts stringbuilder to hold all warnings/errors this._messageTexts = new StringBuilder(); // now we need to scan the universeTable foreach (var uE in _data.Universes) { // if it's still active we'll look into making a socket for it if (cleanStart && uE.Active) { // if it's unicast it's fairly easy to do if (_data.Unicast != null) { // is this the first unicast universe? if (unicastSocket == null) { // yes - make a new socket to use for ALL unicasts unicastSocket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); } // use the common unicastsocket uE.Socket = unicastSocket; IPAddress[] ips = null; try { ips = Dns.GetHostAddresses(_data.Unicast); } catch { //Probably couldn't find the host name NLog.LogManager.GetCurrentClassLogger().Warn("Couldn't connect to host " + _data.Unicast + "."); cleanStart = false; } if (ips != null) { IPAddress ip = null; foreach (IPAddress i in ips) { if (i.AddressFamily == AddressFamily.InterNetwork) { ip = i; } } // try to parse our ip address if (ip == null) { // oops - bad ip, fuss and deactivate NLog.LogManager.GetCurrentClassLogger().Warn("Couldn't connect to host " + _data.Unicast + "."); cleanStart = false; uE.Socket = null; } else { // if good, make our destination endpoint uE.DestIpEndPoint = new IPEndPoint(ip, 5568); } } } // if it's multicast roll up your sleeves we've got work to do else if (_data.Multicast != null) { // create an ipaddress object based on multicast universe ip rules var multicastIpAddress = new IPAddress(new byte[] { 239, 255, (byte)(uE.Universe >> 8), (byte)(uE.Universe & 0xff) }); // create an ipendpoint object based on multicast universe ip/port rules var multicastIpEndPoint = new IPEndPoint(multicastIpAddress, 5568); // first check for multicast id in nictable if (!this._nicTable.ContainsKey(_data.Multicast)) { // no - deactivate and scream & yell!! NLog.LogManager.GetCurrentClassLogger() .Warn("Couldn't connect to use nic " + _data.Multicast + " for multicasting."); if (!_missingInterfaceWarning) { //messageBox Arguments are (Text, Title, No Button Visible, Cancel Button Visible) MessageBoxForm.msgIcon = SystemIcons.Warning; //this is used if you want to add a system icon to the message form. var messageBox = new MessageBoxForm( "The Streaming ACN (E1.31) plugin could not find one or more of the multicast interfaces specified. Please verify your network and plugin configuration.", "Vixen 3 Streaming ACN (E1.31) plugin", false, false); messageBox.ShowDialog(); _missingInterfaceWarning = true; } cleanStart = false; } else { // yes - let's get a working networkinterface object networkInterface = this._nicTable[_data.Multicast]; // have we done this multicast id before? if (nicSockets.ContainsKey(_data.Multicast)) { // yes - easy to do - use existing socket uE.Socket = nicSockets[_data.Multicast]; // setup destipendpoint based on multicast universe ip rules uE.DestIpEndPoint = multicastIpEndPoint; } // is the interface up? else if (networkInterface.OperationalStatus != OperationalStatus.Up) { // no - deactivate and scream & yell!! NLog.LogManager.GetCurrentClassLogger() .Warn("Nic " + _data.Multicast + " is available for multicasting bur currently down."); cleanStart = false; } else { // new interface in 'up' status - let's make a new udp socket uE.Socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); // get a working copy of ipproperties IPInterfaceProperties ipProperties = networkInterface.GetIPProperties(); // get a working copy of all unicasts UnicastIPAddressInformationCollection unicasts = ipProperties.UnicastAddresses; ipAddress = null; foreach (var unicast in unicasts) { if (unicast.Address.AddressFamily == AddressFamily.InterNetwork) { ipAddress = unicast.Address; } } if (ipAddress == null) { this._messageTexts.AppendLine(string.Format("No IP On Multicast Interface: {0} - {1}", networkInterface.Name, uE.InfoToText)); } else { // set the multicastinterface option uE.Socket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.MulticastInterface, ipAddress.GetAddressBytes()); // set the multicasttimetolive option uE.Socket.SetSocketOption( SocketOptionLevel.IP, SocketOptionName.MulticastTimeToLive, 64); // setup destipendpoint based on multicast universe ip rules uE.DestIpEndPoint = multicastIpEndPoint; // add this socket to the socket table for reuse nicSockets.Add(_data.Multicast, uE.Socket); } } } } else { NLog.LogManager.GetCurrentClassLogger() .Warn( "E1.31 plugin failed to start due to unassigned destinations. This can happen with newly created plugin instances that have yet to be configured."); cleanStart = false; } // if still active we need to create an empty packet if (cleanStart) { var zeroBfr = new byte[uE.Size]; var e131Packet = new E131Packet(_data.ModuleInstanceId, "Vixen 3", 0, (ushort)uE.Universe, zeroBfr, 0, uE.Size, _data.Priority, _data.Blind); uE.PhyBuffer = e131Packet.PhyBuffer; } } if (cleanStart) { running = true; } } // any warnings/errors recorded? if (this._messageTexts.Length > 0) { // should we display them if (_data.Warnings) { // show our warnings/errors J1MsgBox.ShowMsg( "The following warnings and errors were detected during startup:", this._messageTexts.ToString(), "Startup Warnings/Errors", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); // discard warning/errors after reporting them this._messageTexts = new StringBuilder(); } } #if VIXEN21 return(new List <Form> { }); #endif }
private void GetLocalIP_DNS() { try { foreach (NetworkInterface Interface in Interfaces) { /* NICs BLACKLIST */ if (Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } if (Interface.Name.Contains("isatap") == true) { continue; } if (Interface.Name.Contains("VMware") == true) { continue; } if (Interface.Name.Contains("Virtual") == true) { continue; } if (Interface.Description.Contains("VMware") == true) { continue; } /* End BlackList*/ UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol) { localAddr.Text = UnicatIPInfo.Address.ToString(); subnetMask.Text = UnicatIPInfo.IPv4Mask.ToString(); NICname.Text = Interface.Description.ToString(); networkCard = Interface.Name.ToString(); long dec_speed = Interface.Speed / 1000000; NICSpeed.Text = dec_speed.ToString() + " Mbps"; switch (Interface.OperationalStatus.ToString()) { case "Up": currentStatus.Text = "CONNECTED"; currentStatus.BackColor = Color.FromArgb(46, 204, 113); break; case "Down": currentStatus.Text = "DISCONNECTED!"; currentStatus.BackColor = Color.FromArgb(231, 76, 60); break; default: currentStatus.Text = Interface.OperationalStatus.ToString(); currentStatus.BackColor = Color.Yellow; break; } var ipInterface = Interface.GetIPProperties(); var gatewayAddresses = ipInterface.GatewayAddresses; if ((gatewayAddresses == null) || (gatewayAddresses.Count == 0)) { gatewayIP.Text = "No Address"; } else { foreach (var gatf in gatewayAddresses) { gatewayIP.Text = gatf.Address.ToString(); } } IPAddressCollection dnsServers = ipInterface.DnsAddresses; foreach (IPAddress dns in dnsServers) { DNSAddress1.Text = dns.ToString(); break; } foreach (IPAddress dns in dnsServers) { DNSAddress2.Text = dns.ToString(); } } } } catch (Exception exp) { MessageBox.Show(exp.Message.ToString(), exp.Source.ToString(), MessageBoxButtons.OK, MessageBoxIcon.Error); } }
// Helper method that marshals the addressinformation into the classes internal static UnicastIPAddressInformationCollection MarshalUnicastIpAddressInformationCollection(IntPtr ptr) { UnicastIPAddressInformationCollection addressList = new UnicastIPAddressInformationCollection(); while (ptr != IntPtr.Zero) { // Get the address IpAdapterUnicastAddress addr = (IpAdapterUnicastAddress)Marshal.PtrToStructure(ptr, typeof(IpAdapterUnicastAddress)); // Add the address to the list addressList.InternalAdd(new SystemUnicastIPAddressInformation(addr)); // Move to the next address in the list ptr = addr.next; } return addressList; }
/// <summary> /// 获取所有默认网关不为空的IP和MAC /// </summary> /// <returns></returns> public static Dictionary <string, string> GetIPAndMacList() { Dictionary <string, string> ipList = new Dictionary <string, string>(); //获取所有网卡信息 NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { //判断是否为以太网卡 //Wireless80211 无线网卡; Ppp 宽带连接;Ethernet 以太网卡 if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { //获取以太网卡网络接口信息 IPInterfaceProperties ip = adapter.GetIPProperties(); //获取单播地址集 UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { //InterNetwork IPV4地址 InterNetworkV6 IPV6地址 //Max MAX 位址 if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork) { string tempIP = ipadd.Address.ToString(); if (ip.GatewayAddresses.Count > 0) { string tempGateway = ip.GatewayAddresses[0].Address.ToString(); if (!string.IsNullOrEmpty(tempGateway) && tempGateway != "0.0.0.0") { string tempMac = adapter.GetPhysicalAddress().ToString(); ipList.Add(tempMac, tempIP); } } } } } else if (adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) { //获取以太网卡网络接口信息 IPInterfaceProperties ip = adapter.GetIPProperties(); //获取单播地址集 UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { //InterNetwork IPV4地址 InterNetworkV6 IPV6地址 //Max MAX 位址 if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork) { string tempIP = ipadd.Address.ToString(); if (ip.GatewayAddresses.Count > 0) { string tempGateway = ip.GatewayAddresses[0].Address.ToString(); if (!string.IsNullOrEmpty(tempGateway) && tempGateway != "0.0.0.0") { string tempMac = adapter.GetPhysicalAddress().ToString(); ipList.Add(tempMac, tempIP); } } } } } } return(ipList); }
public Boolean Connect() { // Both the sender the receiver ipAddressMulticast = IPAddress.Parse(this.Ip); ipEndPointMulticast = new IPEndPoint(this.ipAddressMulticast, this.Port); localEndPoint = new IPEndPoint(IPAddress.Any, this.Port); try { this.udpReceiverConnection = new UdpClient() { ExclusiveAddressUse = false }; udpReceiverConnection.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); udpReceiverConnection.Client.Bind(localEndPoint); // join multicast group on all available network interfaces NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface networkInterface in networkInterfaces) { if ((!networkInterface.Supports(NetworkInterfaceComponent.IPv4)) || (networkInterface.OperationalStatus != OperationalStatus.Up)) { continue; } IPInterfaceProperties adapterProperties = networkInterface.GetIPProperties(); UnicastIPAddressInformationCollection unicastIPAddresses = adapterProperties.UnicastAddresses; IPAddress ipAddress = null; foreach (UnicastIPAddressInformation unicastIPAddress in unicastIPAddresses) { if (unicastIPAddress.Address.AddressFamily != AddressFamily.InterNetwork) { continue; } ipAddress = unicastIPAddress.Address; break; } if (ipAddress == null) { continue; } if (SelectedInterfaces != null && !SelectedInterfaces.Contains(ipAddress.ToString())) { continue; } udpReceiverConnection.JoinMulticastGroup(ipAddressMulticast, ipAddress); // Also create a client for this interface and add it to the list of interfaces IPEndPoint interfaceEndPoint = new IPEndPoint(ipAddress, this.Port); UdpClient sendClient = new UdpClient(); sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); sendClient.Client.MulticastLoopback = true; sendClient.Client.Bind(interfaceEndPoint); sendClient.JoinMulticastGroup(ipAddressMulticast); if (udpSenderConnections == null) { udpSenderConnections = new List <UdpClient>(); } udpSenderConnections.Add(sendClient); } } catch { return(false); } this.isConnected = true; StartReceiver(); return(isConnected); }
private static UnicastIPAddressInformationCollection GetUnicastAddressTable() { UnicastIPAddressInformationCollection rval = new UnicastIPAddressInformationCollection(); NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); for (int i = 0; i < interfaces.Length; ++i) { UnicastIPAddressInformationCollection addresses = interfaces[i].GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation address in addresses) { if (!rval.Contains(address)) { rval.InternalAdd(address); } } } return rval; }
/// <summary> /// Obtiene el estado DAD de la Ip asignada a TCP /// </summary> /// <returns>un estado de la clase IpState</returns> internal static int getIpState(NetworkAdapter networkAdapter, IPAddress ipAdress) { try { int ipState = IpState.NOTFOUND; INetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (INetworkInterface networkInterface in networkInterfaces) { if (networkAdapter.Name.Equals(networkInterface.Name)) { UnicastIPAddressInformationCollection uaddresses = networkInterface.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation unicastAddress in uaddresses) { if (ipAdress.ToString().Equals(unicastAddress.Address.ToString())) { switch (unicastAddress.DuplicateAddressDetectionState) { case DuplicateAddressDetectionState.Deprecated: { ipState = IpState.INVALID; break; } case DuplicateAddressDetectionState.Duplicate: { ipState = IpState.DUPLICATE; break; } case DuplicateAddressDetectionState.Invalid: { ipState = IpState.INVALID; break; } case DuplicateAddressDetectionState.Preferred: { ipState = IpState.VALID; break; } case DuplicateAddressDetectionState.Tentative: { ipState = IpState.VALID; break; } } break; } } break; } } return(ipState); } catch (ThreadAbortException e) { throw e; } catch (Exception e) { throw e; } }
private void Refresh() { if (NetworkInterface.GetIsNetworkAvailable() == true) { IpAddress.Visibility = Visibility.Visible; IpAddressLabel.Visibility = Visibility.Visible; DNSIP.Visibility = Visibility.Visible; DNSIPLabel.Visibility = Visibility.Visible; DG.Visibility = Visibility.Visible; DGLabel.Visibility = Visibility.Visible; GlobalIp.Visibility = Visibility.Visible; GlobalIpLabel.Visibility = Visibility.Visible; error.Visibility = Visibility.Collapsed; NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface Interface in Interfaces) { if (Interface.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } IPInterfaceProperties ipProperties = Interface.GetIPProperties(); IPAddressCollection dnsAddresses = ipProperties.DnsAddresses; foreach (IPAddress dnsAdress in dnsAddresses) { DNSIP.Content = dnsAdress; } UnicastIPAddressInformationCollection UnicastIPInfoCol = Interface.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation UnicatIPInfo in UnicastIPInfoCol) { IpAddress.Content = UnicatIPInfo.Address + "/"; } } /*new Thread(() => * { * try * { * string externalip = new WebClient().DownloadString("http://icanhazip.com"); * GlobalIp.Content = externalip; * } * catch(Exception) * { * * } * }).Start();*/ DG.Content = NetworkInterface.GetAllNetworkInterfaces().Where(n => n.OperationalStatus == OperationalStatus.Up).Where(n => n.NetworkInterfaceType != NetworkInterfaceType.Loopback).SelectMany(n => n.GetIPProperties()?.GatewayAddresses).Select(g => g?.Address).Where(a => a != null).FirstOrDefault(); if (IpAddress.Content == "/") { IpAddress.Content = "No have Ip address"; } if (DNSIP.Content == "") { DNSIP.Content = "No have DNS address"; } if (DG.Content == "") { DG.Content = "No have Default Getway Address"; } } else { IpAddress.Visibility = Visibility.Collapsed; IpAddressLabel.Visibility = Visibility.Collapsed; DNSIP.Visibility = Visibility.Collapsed; DNSIPLabel.Visibility = Visibility.Collapsed; DG.Visibility = Visibility.Collapsed; DGLabel.Visibility = Visibility.Collapsed; GlobalIp.Visibility = Visibility.Collapsed; GlobalIpLabel.Visibility = Visibility.Collapsed; error.Visibility = Visibility.Visible; } }
/// <summary> /// Returns a list of IP Addresses /// </summary> /// <param name="allowIPV6">If true, IPv6 addresses will be preferred. If false, only IPv4 addresses will be returned</param> /// <returns></returns> internal static IList <IPAddress> GetLocalAddresses(bool allowIPV6) { List <IPAddress> list = new List <IPAddress>(); if (!NetworkInterface.GetIsNetworkAvailable()) { // No Network is available. Return a loopback address if (allowIPV6) { list.Add(IPAddress.IPv6Loopback); } else { list.Add(IPAddress.Loopback); } return(list); } foreach (NetworkInterface ni in NetworkInterface.GetAllNetworkInterfaces()) { // Disallow VPN connections // If they are necessary, configure the agent manually to us it if (ni.OperationalStatus == OperationalStatus.Up && ni.NetworkInterfaceType != NetworkInterfaceType.Loopback && ni.NetworkInterfaceType != NetworkInterfaceType.Ppp) { IPInterfaceProperties niProperties = ni.GetIPProperties(); UnicastIPAddressInformationCollection addresses = niProperties.UnicastAddresses; bool added = false; if (allowIPV6 && ni.Supports(NetworkInterfaceComponent.IPv6)) { foreach (UnicastIPAddressInformation uipi in addresses) { if (uipi.IPv4Mask.Equals(IPAddress.Any)) { // Add Ipv6 addresses to the front of the list list.Insert(0, uipi.Address); added = true; break; } } } // If we haven't added an address from this network adaptor yet in our // IPv6 search above, add it now, if possible if (!added && ni.Supports(NetworkInterfaceComponent.IPv4)) { IPv4InterfaceProperties ipv4ip = niProperties.GetIPv4Properties(); if (ipv4ip != null) { foreach (UnicastIPAddressInformation uipi in addresses) { if (!uipi.IPv4Mask.Equals(IPAddress.Any)) { list.Add(uipi.Address); break; } } } } } } return(list); }
private static UnicastIPAddressInformationCollection GetUnicastAddressTable() { UnicastIPAddressInformationCollection informations = new UnicastIPAddressInformationCollection(); NetworkInterface[] allNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); for (int i = 0; i < allNetworkInterfaces.Length; i++) { foreach (UnicastIPAddressInformation information in allNetworkInterfaces[i].GetIPProperties().UnicastAddresses) { if (!informations.Contains(information)) { informations.InternalAdd(information); } } } return informations; }
public static void WakeUp(string mac, string network, int udpPort, int ttl) { UdpClient client = default(UdpClient); IPEndPoint localEndPoint = default(IPEndPoint); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); //GetAllNetworkInterfaces retourne un tableau qui contint une instance de cet classe byte[] packet = new byte[102]; int i = default(int), j = default(int); byte[] macBytes = default(byte[]); try { macBytes = Form2.GetMac1(mac); // WOL packet contains a 6-bytes header and 16 times a 6-bytes sequence containing the MAC address. // packet = byte(17 * 6) // Header of 0xFF 6 times. for (i = 0; i <= 5; i++) { packet[i] = 255; } // Body of magic packet contains the MAC address repeated 16 times. for (i = 1; i <= 16; i++) { for (j = 0; j <= 5; j++) { packet[(i * 6) + j] = macBytes[j]; } } /* * for (int p = 0; p < packet.Length; p++) * { MessageBox.Show(packet[p].ToString()); } */ foreach (NetworkInterface adapter in nics) { // Only display informatin for interfaces that support IPv4. if (adapter.Supports(NetworkInterfaceComponent.IPv4) == false) { continue; } // UnicastIPAddressInformationCollection addresses = adapter.GetIPProperties.UnicastAddresses; UnicastIPAddressInformationCollection addresses = adapter.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation address in addresses) { if (address.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { localEndPoint = new IPEndPoint(IPAddress.Parse(address.Address.ToString()), udpPort); // Debug.WriteLine("Interface: " + localEndPoint.ToString()); try { client = new UdpClient(); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true); client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, true); client.ExclusiveAddressUse = false; client.Client.Bind(localEndPoint); client.Connect(network, udpPort); client.EnableBroadcast = true; client.Ttl = (short)ttl; client.Send(packet, packet.Length); } catch { } } } } } catch (Exception ex) { throw; } }
private static NetworkInterfaceInfo GetInterfaces() { // Since many of the methods in java.net.NetworkInterface end up calling this method and the underlying stuff this is // based on isn't very quick either, we cache the array for a couple of seconds. if (cache != null && DateTime.UtcNow - cachedSince < new TimeSpan(0, 0, 5)) { return(cache); } NetworkInterface[] ifaces = NetworkInterface.GetAllNetworkInterfaces(); // on Mono (on Windows) we need to filter out the network interfaces that don't have any IP properties ifaces = Array.FindAll(ifaces, IsValid); Array.Sort(ifaces, Compare); java.net.NetworkInterface[] ret = new java.net.NetworkInterface[ifaces.Length]; int eth = 0; int tr = 0; int fddi = 0; int lo = 0; int ppp = 0; int sl = 0; int net = 0; for (int i = 0; i < ifaces.Length; i++) { string name; switch (ifaces[i].NetworkInterfaceType) { case NetworkInterfaceType.Ethernet: name = "eth" + eth++; break; case NetworkInterfaceType.TokenRing: name = "tr" + tr++; break; case NetworkInterfaceType.Fddi: name = "fddi" + fddi++; break; case NetworkInterfaceType.Loopback: if (lo > 0) { continue; } name = "lo"; lo++; break; case NetworkInterfaceType.Ppp: name = "ppp" + ppp++; break; case NetworkInterfaceType.Slip: name = "sl" + sl++; break; default: name = "net" + net++; break; } java.net.NetworkInterface netif = new java.net.NetworkInterface(); ret[i] = netif; netif._set1(name, ifaces[i].Description, GetIndex(ifaces[i])); UnicastIPAddressInformationCollection uipaic = ifaces[i].GetIPProperties().UnicastAddresses; List <java.net.InetAddress> addresses = new List <java.net.InetAddress>(); List <java.net.InterfaceAddress> bindings = new List <java.net.InterfaceAddress>(); for (int j = 0; j < uipaic.Count; j++) { IPAddress addr = uipaic[j].Address; if (addr.AddressFamily == AddressFamily.InterNetwork) { java.net.Inet4Address address = new java.net.Inet4Address(null, addr.GetAddressBytes()); java.net.InterfaceAddress binding = new java.net.InterfaceAddress(); short mask = 32; java.net.Inet4Address broadcast = null; IPAddress v4mask; try { v4mask = uipaic[j].IPv4Mask; } catch (NotImplementedException) { // Mono (as of 2.6.7) doesn't implement the IPv4Mask property v4mask = null; } if (v4mask != null && !v4mask.Equals(IPAddress.Any)) { broadcast = new java.net.Inet4Address(null, -1); mask = 0; foreach (byte b in v4mask.GetAddressBytes()) { mask += (short)java.lang.Integer.bitCount(b); } } else if (address.isLoopbackAddress()) { mask = 8; broadcast = new java.net.Inet4Address(null, 0xffffff); } binding._set(address, broadcast, mask); addresses.Add(address); bindings.Add(binding); } else if (Java_java_net_InetAddressImplFactory.isIPv6Supported()) { int scope = 0; if (addr.IsIPv6LinkLocal || addr.IsIPv6SiteLocal) { scope = (int)addr.ScopeId; } java.net.Inet6Address ia6 = new java.net.Inet6Address(); ia6._holder().ipaddress = addr.GetAddressBytes(); if (scope != 0) { ia6._holder().scope_id = scope; ia6._holder().scope_id_set = true; ia6._holder().scope_ifname = netif; ia6._holder().scope_ifname_set = true; } java.net.InterfaceAddress binding = new java.net.InterfaceAddress(); // TODO where do we get the IPv6 subnet prefix length? short mask = 128; binding._set(ia6, null, mask); addresses.Add(ia6); bindings.Add(binding); } } netif._set2(addresses.ToArray(), bindings.ToArray(), new java.net.NetworkInterface[0]); } NetworkInterfaceInfo nii = new NetworkInterfaceInfo(); nii.dotnetInterfaces = ifaces; nii.javaInterfaces = ret; cache = nii; cachedSince = DateTime.UtcNow; return(nii); }
public static NetworkInterface AutoAdapter() { IPAddress IPaddress = null; List <IPAddress> DNS_IP = new List <IPAddress>(); NetworkInterface[] Interfaces = NetworkInterface.GetAllNetworkInterfaces(); bool hasGateway = false; bool FoundAdapter = false; foreach (NetworkInterface adapter in Interfaces) { if (adapter.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } if (adapter.OperationalStatus == OperationalStatus.Up) { UnicastIPAddressInformationCollection IPInfoCollection = adapter.GetIPProperties().UnicastAddresses; IPInterfaceProperties properties = adapter.GetIPProperties(); foreach (UnicastIPAddressInformation IPAddressInfo in IPInfoCollection) { if (//IPAddressInfo.DuplicateAddressDetectionState == DuplicateAddressDetectionState.Preferred & //IPAddressInfo.AddressPreferredLifetime != UInt32.MaxValue & IPAddressInfo.Address.AddressFamily == AddressFamily.InterNetwork) { Log_Info("Matched Adapter"); IPaddress = IPAddressInfo.Address; FoundAdapter = true; break; } } foreach (IPAddress DNSaddress in properties.DnsAddresses) //allow more than one DNS address? { if (FoundAdapter == true) { if (!(DNSaddress.AddressFamily == AddressFamily.InterNetworkV6)) { DNS_IP.Add(DNSaddress); } } } GatewayIPAddressInformationCollection GatewayInfoCollection = properties.GatewayAddresses; foreach (GatewayIPAddressInformation GatewayInfo in GatewayInfoCollection) { if (GatewayInfo.Address.AddressFamily == AddressFamily.InterNetwork) { hasGateway = true; break; } } if (DNS_IP.Count == 0 | hasGateway == false) { //adapter not suitable hasGateway = false; DNS_IP.Clear(); FoundAdapter = false; } } if (FoundAdapter == true) { Log_Info(adapter.Name); Log_Info(adapter.Description); Log_Verb("IP Address :" + IPaddress.ToString()); Log_Verb("Domain Name :" + Dns.GetHostName()); //Error.WriteLine("Subnet Mask :" + NetMask.ToString()); //Error.WriteLine("Gateway IP :" + GatewayIP.ToString()); Log_Verb("DNS 1 : " + DNS_IP[0].ToString()); return(adapter); } } return(null); }
// Created method for gathering user IP and writing to text file static void WriteNetConfig() { // You can change the last component in parameter to add bat file to different location string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Console input for naming the file // The string "file" saves .bat to the end of the string so that when it is saved to the location of choice, it creates a functional .bat file Console.Write("Enter the name of the batch file you wish to create: "); string fileName = Console.ReadLine(); string file = fileName + ".bat"; try { // Deleting file name if name already exisits if (File.Exists(Path.Combine(docPath, file))) { File.Delete(Path.Combine(docPath, file)); Console.WriteLine(); Console.WriteLine(file + " file name already in use."); Console.WriteLine("Deleting " + file + " and rewriting!"); } // Writing net configuration (IPv4 address, subnet mask, default gateway, DNS servers) to batch file using (StreamWriter fileWrite = File.CreateText(Path.Combine(docPath, file))) { // Gathering local IPv4 address #region string ipAdd = ""; string userIP = ""; IPHostEntry host; host = Dns.GetHostEntry(ipAdd); foreach (IPAddress ip in host.AddressList) { if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { userIP = ip.ToString(); } } #endregion // Gathering the subnet mask #region string subnetMask = ""; NetworkInterface[] netInterfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface subMask in netInterfaces) { if (subMask.OperationalStatus == OperationalStatus.Up) { if (subMask.NetworkInterfaceType == NetworkInterfaceType.Loopback) { continue; } UnicastIPAddressInformationCollection UnicastIPInfo = subMask.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation subnet in UnicastIPInfo.Skip(1)) { subnetMask = subnet.IPv4Mask.ToString(); } } } #endregion // Gathering the default gateway #region IPAddress defGateway = null; var netAdapt = NetworkInterface.GetAllNetworkInterfaces(); if (netAdapt.Any()) { foreach (var adapter in netAdapt) { var ipProper = adapter.GetIPProperties(); if (ipProper == null) { continue; } var gateway1 = ipProper.GatewayAddresses; if (!gateway1.Any()) { continue; } var gateway2 = gateway1.FirstOrDefault(g => g.Address.AddressFamily.ToString() == "InterNetwork"); if (gateway2 == null) { continue; } defGateway = gateway2.Address; } } #endregion // Gathering the DNS server information #region string primaryDNS = ""; string alternateDNS = ""; foreach (NetworkInterface dnsServers in netInterfaces) { if (dnsServers.OperationalStatus == OperationalStatus.Up) { IPInterfaceProperties ipProperties = dnsServers.GetIPProperties(); IPAddressCollection dnsAddresses = ipProperties.DnsAddresses; // Returns the first address for DNS servers by using .Take foreach (IPAddress dns in dnsAddresses.Take(1)) { primaryDNS = dns.ToString(); } // Returns the second address for DNS servers by using .Skip(1) foreach (IPAddress dns in dnsAddresses.Skip(1)) { alternateDNS = dns.ToString(); } break; } } #endregion // Gathering the network adapter name to be included into the batch file #region string adapterName = ""; foreach (NetworkInterface netAdapter in netInterfaces) { // If check for getting just the currently connected adapters as well as excluding the tunnel and loopback adapters if (netAdapter.OperationalStatus == OperationalStatus.Up && netAdapter.NetworkInterfaceType != NetworkInterfaceType.Tunnel && netAdapter.NetworkInterfaceType != NetworkInterfaceType.Loopback) { adapterName = netAdapter.Name; } } #endregion // Writing the batch file script fileWrite.WriteLine("@echo off"); fileWrite.WriteLine("netsh interface ipv4 set address name=\"" + adapterName + "\" static " + userIP + " " + subnetMask + " " + defGateway); fileWrite.WriteLine(); fileWrite.WriteLine("@echo off"); fileWrite.WriteLine("netsh interface ipv4 set dns name=\"" + adapterName + "\" static " + primaryDNS + ""); fileWrite.WriteLine("netsh interface ipv4 add dns name=\"" + adapterName + "\" " + alternateDNS + " index=2"); } // FInal console output Console.WriteLine(); Console.WriteLine(file + " has successfully been created and added to user's desktop!"); Console.WriteLine(); Console.WriteLine("Press ENTER to exit...."); Console.ReadLine(); } catch (Exception MyExcep) { Console.WriteLine(MyExcep.ToString()); } }
private void UpdateNetworkInformation() { lstAddress.Items.Clear(); // 取得支援IP通訊協定之網路介面卡的相關資訊 IPInterfaceProperties ipProperties = selectedInterface.GetIPProperties(); // 取得DHCP伺服器位址 IPAddressCollection ipAddresses = ipProperties.DhcpServerAddresses; foreach (IPAddress ipAddress in ipAddresses) { addIPAddress("DHCP伺服器", ipAddress); } // 取得網路介面卡所設定之DNS伺服器位址 ipAddresses = ipProperties.DnsAddresses; foreach (IPAddress ipAddress in ipAddresses) { addIPAddress("DNS伺服器", ipAddress); } // 取得WINS伺服器的位址 ipAddresses = ipProperties.WinsServersAddresses; foreach (IPAddress ipAddress in ipAddresses) { addIPAddress("WINS伺服器", ipAddress); } // 取得網路介面卡的網路閘道位址 GatewayIPAddressInformationCollection gatewayInfo = ipProperties.GatewayAddresses; foreach (GatewayIPAddressInformation info in gatewayInfo) { addIPAddress("網路閘道", info.Address); } // 取得網路介面卡的Anycast IP位址 IPAddressInformationCollection anycastInfo = ipProperties.AnycastAddresses; foreach (IPAddressInformation info in anycastInfo) { addIPAddress("Anycast", info.Address); } // 取得網路介面卡的多點播送位址 MulticastIPAddressInformationCollection multicastInfo = ipProperties.MulticastAddresses; foreach (MulticastIPAddressInformation info in multicastInfo) { addIPAddress("多點播送", info.Address); } // 取得網路介面卡的單點傳送位址 UnicastIPAddressInformationCollection unicastInfo = ipProperties.UnicastAddresses; foreach (UnicastIPAddressInformation info in unicastInfo) { addIPAddress("單點傳送", info.Address); } }
/// <summary> /// 取网卡信息 /// </summary> /// <returns></returns> public static string GetNetAdapterInfo() { StringBuilder sb = new StringBuilder(); NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); if (adapters != null) { foreach (NetworkInterface ni in adapters) { string fCardType = "未知网卡"; IPInterfaceProperties ips = ni.GetIPProperties(); PhysicalAddress pa = ni.GetPhysicalAddress(); if (pa == null) { continue; } string pastr = pa.ToString(); if (pastr.Length < 7) { continue; } if (pastr.Substring(0, 6) == "000000") { continue; } if (ni.Name.ToLower().IndexOf("vmware") > -1) { continue; } string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + ni.Id + "\\Connection"; RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false); if (rk != null) { // 区分 PnpInstanceID // 如果前面有 PCI 就是本机的真实网卡 // MediaSubType 为 01 则是常见网卡,02为无线网卡。 string fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString(); int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0)); if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI") { if (ni.NetworkInterfaceType.ToString().ToLower().IndexOf("wireless") == -1) { fCardType = "物理网卡"; } else { fCardType = "无线网卡"; } } else if (fMediaSubType == 1 || fMediaSubType == 0) { fCardType = "虚拟网卡"; } else if (fMediaSubType == 2 || ni.NetworkInterfaceType.ToString().ToLower().IndexOf("wireless") > -1) { fCardType = "无线网卡"; } else if (fMediaSubType == 7) { fCardType = "蓝牙"; } } StringBuilder isb = new StringBuilder(); UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = ips.UnicastAddresses; foreach (UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection) { if (UnicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { isb.Append(string.Format("Ip Address: {0}", UnicastIPAddressInformation.Address) + "\r\n"); // Ip 地址 } } // IPAddressCollection ipc = ips.DnsAddresses; //if (ipc.Count > 0) //{ // foreach (IPAddress ip in ipc) // { // isb.Append(string.Format("DNS服务器地址:{0}\r\n",ip)); // } //} string s = string.Format("{0}\r\n描述信息:{1}\r\n类型:{2}\r\n速度:{3} MB\r\nMac地址:{4}\r\n{5}", fCardType, ni.Name, ni.NetworkInterfaceType, ni.Speed / 1024 / 1024, ni.GetPhysicalAddress(), isb.ToString()); sb.Append(s + "\r\n"); } } return(sb.ToString()); }
public static List <String> GetLocalIP() { List <ServiceHost> serviceHostPool = new List <ServiceHost>(); NetworkInterface[] interfaces = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); List <String> ipaddrs = new List <string>(); ManagementClass mcNetworkAdapterConfig = new ManagementClass("Win32_NetworkAdapterConfiguration"); ManagementObjectCollection moc_NetworkAdapterConfig = mcNetworkAdapterConfig.GetInstances(); foreach (ManagementObject mo in moc_NetworkAdapterConfig) { string mServiceName = mo["ServiceName"] as string; //过滤非真实的网卡 if (!(bool)mo["IPEnabled"]) { continue; } if (mServiceName.ToLower().Contains("vmnetadapter") || mServiceName.ToLower().Contains("vmware") || mServiceName.ToLower().Contains("ppoe") || mServiceName.ToLower().Contains("bthpan") || mServiceName.ToLower().Contains("tapvpn") || mServiceName.ToLower().Contains("ndisip") || mServiceName.ToLower().Contains("sinforvnic")) { continue; } string[] mIPAddress = mo["IPAddress"] as string[]; if (mIPAddress != null) { foreach (string ip in mIPAddress) { if (ip != "0.0.0.0") { ipaddrs.Add(ip); } } } mo.Dispose(); } List <String> ipaddrs2 = new List <string>(); foreach (NetworkInterface adapter in nics) { string hostIP = String.Empty; if (adapter.Name.Contains("vEthernet")) { continue; } //判断是否为以太网卡 //Wireless80211 无线网卡; Ppp 宽带连接;Ethernet 以太网卡 if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { //获取以太网卡网络接口信息 IPInterfaceProperties ip = adapter.GetIPProperties(); //获取单播地址集 UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { if (ipadd.SuffixOrigin == SuffixOrigin.LinkLayerAddress) { continue; } //InterNetwork IPV4地址 InterNetworkV6 IPV6地址 //Max MAX 位址 if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork) { ipaddrs2.Add(ipadd.Address.ToString()); } } } else if (adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) { //获取以太网卡网络接口信息 IPInterfaceProperties ip = adapter.GetIPProperties(); //获取单播地址集 UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { if (ipadd.SuffixOrigin == SuffixOrigin.LinkLayerAddress) { continue; } //InterNetwork IPV4地址 InterNetworkV6 IPV6地址 //Max MAX 位址 if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork) { ipaddrs2.Add(ipadd.Address.ToString()); } } } } ipaddrs.RemoveAll(p => !ipaddrs2.Contains(p)); return(ipaddrs); }
private string GetIPAddresses(IPInterfaceProperties adapterProperties) { StringBuilder ipAddressesBuilder = new StringBuilder(); IPAddressCollection dnsServers = adapterProperties.DnsAddresses; if (dnsServers.Count > 0) { foreach (IPAddress dns in dnsServers) { ipAddressesBuilder.AppendFormat(" DNS Server ................. : {0}\n", dns.ToString()); } } GatewayIPAddressInformationCollection gateways = adapterProperties.GatewayAddresses; if (gateways.Count > 0) { foreach (GatewayIPAddressInformation gatewayAddresssInfo in gateways) { ipAddressesBuilder.AppendFormat(" Gateway Address ............ : {0}\n", gatewayAddresssInfo.Address); } } IPAddressCollection dhcpServers = adapterProperties.DhcpServerAddresses; if (dhcpServers.Count > 0) { foreach (IPAddress dhcpServer in dhcpServers) { ipAddressesBuilder.AppendFormat(" DHCP Server ................ : {0}\n", dhcpServer); } } IPAddressInformationCollection anyCast = adapterProperties.AnycastAddresses; if (anyCast.Count > 0) { foreach (IPAddressInformation any in anyCast) { ipAddressesBuilder.AppendFormat(" Anycast Address ............ : {0} {1} {2}\n", any.Address, any.IsTransient ? "Transient" : String.Empty, any.IsDnsEligible ? "DNS Eligible" : String.Empty); } } MulticastIPAddressInformationCollection multiCast = adapterProperties.MulticastAddresses; if (multiCast.Count > 0) { foreach (IPAddressInformation multi in multiCast) { ipAddressesBuilder.AppendFormat(" Multicast Address .......... : {0} {1} {2}\n", multi.Address, multi.IsTransient ? "Transient" : String.Empty, multi.IsDnsEligible ? "DNS Eligible" : String.Empty); } } UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; if (uniCast.Count > 0) { string lifeTimeFormat = "dddd, MMMM dd, yyyy hh:mm:ss tt"; foreach (UnicastIPAddressInformation uni in uniCast) { DateTime when; ipAddressesBuilder.AppendFormat(" Unicast Address ............ : {0}\n", uni.Address); ipAddressesBuilder.AppendFormat(" Prefix Origin ............. : {0}\n", uni.PrefixOrigin); ipAddressesBuilder.AppendFormat(" Suffix Origin ............. : {0}\n", uni.SuffixOrigin); ipAddressesBuilder.AppendFormat(" Duplicate Address Detection : {0}\n", uni.DuplicateAddressDetectionState); // Format the lifetimes as Saturday, March 13, 2010 11:33:44 PM // if en-us is the current culture. // Calculate the date and time at the end of the lifetimes. when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressValidLifetime); when = when.ToLocalTime(); ipAddressesBuilder.AppendFormat(" Valid Life Time ........... : {0}\n", when.ToString(lifeTimeFormat, new CultureInfo("en-US"))); when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressPreferredLifetime); when = when.ToLocalTime(); ipAddressesBuilder.AppendFormat(" Preferred life time ....... : {0}\n", when.ToString(lifeTimeFormat, new CultureInfo("en-US"))); when = DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime); when = when.ToLocalTime(); ipAddressesBuilder.AppendFormat(" DHCP Leased Life Time ..... : {0}\n", when.ToString(lifeTimeFormat, new CultureInfo("en-US"))); } } return(ipAddressesBuilder.ToString()); }
static ServiceEnvironment() { Process process = Process.GetCurrentProcess(); _serviceName = GetAppNamespace(process); _computerName = Environment.MachineName; _workPath = AppContext.BaseDirectory; _pid = process.Id; _processInfo = string.Format("{0}-{1}", _pid, process.ProcessName); try { // 这种方式在linux上面只能获取到一个127.0.0.1,其他什么都获取不到,只能用下面的方式,DNS方式只适合winx 遍历网卡方式都适用 //string host = Dns.GetHostName(); //var addrs = Dns.GetHostAddresses(host); //foreach (var a in addrs) //{ // if (a.AddressFamily == AddressFamily.InterNetwork) // { // if (a.ToString() == "127.0.0.1" ||string.IsNullOrEmpty(a.ToString())) // { // continue; // } // //_computerAddress = a.ToString(); // //break; // if (_ipList.Count==0) // 第一个 // { // _computerAddress = a.ToString(); // } // _ipList.Add(a.ToString()); // } //} NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces(); foreach (var item in interfaces) { if (item.NetworkInterfaceType == NetworkInterfaceType.Ethernet) { IPInterfaceProperties ipInterfaceProperties = item.GetIPProperties(); UnicastIPAddressInformationCollection ipCollection = ipInterfaceProperties.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { var ip = ipadd.Address; if (ip.AddressFamily == AddressFamily.InterNetwork) { if (ip.ToString() == "127.0.0.1" || string.IsNullOrEmpty(ip.ToString())) { continue; } if (_ipList.Count == 0) // 第一个 { _computerAddress = ip.ToString(); } _ipList.Add(ip.ToString()); } } } } } catch (Exception) { _computerAddress = "0.0.0.0"; } _environmentInfo = string.Format("[serviceName]:{0} [computerName]:{1} [workPath]:{2} [processInfo]:{3} [computerAddress]:{4}", ServerSetting.AppName, _computerName, _workPath, _processInfo, _computerAddress); }
private void Button_Click(object sender, RoutedEventArgs e) { if (link_button.Content.ToString() != "断开") { try { link_button.IsEnabled = false; string pppoe_id = "ctcc";//默认电信线路的账号 string pppoe_pw = "123"; if (lt_Radio.IsChecked == true) { pppoe_id = "cucc"; } //使用匿名委托传递多个参数 Thread th = new Thread(delegate() { pppoe.pppoe_on(pppoe_id, pppoe_pw); }); th.IsBackground = true; Console.WriteLine("--------Link-------start----------"); th.Start(); Thread.Sleep(500); NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();//获取本机所有网卡对象 foreach (NetworkInterface adapter in adapters) { Console.WriteLine("获取本地IP:" + adapter.NetworkInterfaceType + " " + adapter.Description.ToString()); if (adapter.Description.Contains("CYJH")) //枚举条件:描述中包含"CYJH"" { IPInterfaceProperties ipProperties = adapter.GetIPProperties(); //获取IP配置 UnicastIPAddressInformationCollection ipCollection = ipProperties.UnicastAddresses; //获取单播地址集 foreach (UnicastIPAddressInformation ip in ipCollection) { if (ip.Address.AddressFamily == AddressFamily.InterNetwork) //只要ipv4的 { Label_Bendi.Content = ip.Address; //获取ip } } if (adapter.OperationalStatus == OperationalStatus.Up) { Label_Zhuangtai.Content = "已连接"; link_button.Content = "断开"; } } } link_button.IsEnabled = true; dx_Radio.IsEnabled = false; lt_Radio.IsEnabled = false; GetIP(); Console.WriteLine("--------Link-------OK"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); //throw; } } else { link_button.IsEnabled = false; link_button.Content = "连接"; pppoe.pppoe_off(); Thread.Sleep(1000); GetIP(); Label_Zhuangtai.Content = "未连接"; link_button.IsEnabled = true; dx_Radio.IsEnabled = true; lt_Radio.IsEnabled = true; } }
public static void Main(string[] args) { //string for argument from user string str = ""; bool match = false; //check if user provided arguments //if argument provided make it into a string if (args.Length > 0) { for (int i = 0; i < args.Length; i++) { str = str + " " + args[i]; } } IPGlobalProperties prop = IPGlobalProperties.GetIPGlobalProperties(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); IPGlobalProperties gp = IPGlobalProperties.GetIPGlobalProperties(); //... ... Console.WriteLine("Windows IP Configuration"); Console.WriteLine(); Console.WriteLine(" Host name . . . . . . . . . . . . : {0}", prop.HostName); Console.WriteLine(" Primary DNS Suffix . . . . . . . : {0}", nics[0].GetIPProperties().DnsSuffix); Console.WriteLine(); //... ... foreach (NetworkInterface adapter in nics) { String address = adapter.GetPhysicalAddress().ToString(); IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses; UnicastIPAddressInformationCollection UnicastIPInfoCol = adapter.GetIPProperties().UnicastAddresses; if (adapter.NetworkInterfaceType.Equals(NetworkInterfaceType.Wireless80211)) { string interfaceType = "Wireless LAN"; //check if user input is a part of adapter name string name = interfaceType + " adapter " + adapter.Name; if (name.Contains(str)) { match = true; Console.WriteLine("{0} adapter {1}:", interfaceType, adapter.Name); Console.WriteLine("\tDescription: {0}", adapter.Description.ToString()); Console.WriteLine("\tConnection-Specific DNS Suffix . . . . . . . : {0}", nics[0].GetIPProperties().DnsSuffix); //check if there exists a default gateway address if (addresses.Count == 0) { Console.WriteLine("\tDefault Gateway : . . . . . . . . . . :"); } else { foreach (GatewayIPAddressInformation ad in addresses) { Console.WriteLine("\tDefault Gateway . . . . . . . . . . : {0}", ad.Address.ToString()); } } IPAddress ad0 = UnicastIPInfoCol[0].Address; if (ad0.IsIPv6LinkLocal) { Console.WriteLine("\tLink-local Ipv6 Address . . . . . . . . . . : {0}", ad0); } else { Console.WriteLine("\tIPv6 Address . . . . . . . . . . : {0}", ad0); } for (int i = 1; i < UnicastIPInfoCol.Count; i++) { if (UnicastIPInfoCol[i].Address.ToString().Contains(":")) { Console.WriteLine("\tIPv6 Address . . . . . . . . . . : {0}", UnicastIPInfoCol[i].Address); } else { Console.WriteLine("\tIPv4 Address . . . . . . . . . . : {0}", UnicastIPInfoCol[i].Address); Console.WriteLine("\tSubnet Mask . . . . . . . . . . : {0}", UnicastIPInfoCol[i].IPv4Mask); } } } } if (adapter.NetworkInterfaceType.Equals(NetworkInterfaceType.Ethernet)) { string interfaceType = "Ethernet"; //check if user input is a part of adapter name string name = interfaceType + " adapter " + adapter.Name; if (name.Contains(str)) { match = true; Console.WriteLine("{0} adapter {1}:", interfaceType, adapter.Name); Console.WriteLine("\tDescription: {0}", adapter.Description.ToString()); Console.WriteLine("\tConnection-Specific DNS Suffix . . . . . . . : {0}", nics[0].GetIPProperties().DnsSuffix); //check if there exists a default gateway address if (addresses.Count == 0) { Console.WriteLine("\tDefault Gateway . . . . . . . . . . :"); } else { foreach (GatewayIPAddressInformation ad in addresses) { Console.WriteLine("\tDefault Gateway : . . . . . . . . . . {0}", ad.Address.ToString()); } } IPAddress ad0 = UnicastIPInfoCol[0].Address; if (ad0.IsIPv6LinkLocal) { Console.WriteLine("\tLink-local Ipv6 Address . . . . . . . . . . : {0}", ad0); } else { Console.WriteLine("\tIPv6 Address . . . . . . . . . . : {0}", ad0); } for (int i = 1; i < UnicastIPInfoCol.Count; i++) { if (UnicastIPInfoCol[i].Address.ToString().Contains(":")) { Console.WriteLine("\tIPv6 Address . . . . . . . . . . : {0}", UnicastIPInfoCol[i].Address); } else { Console.WriteLine("\tIPv4 Address . . . . . . . . . . : {0}", UnicastIPInfoCol[i].Address); Console.WriteLine("\tSubnet Mask . . . . . . . . . . : {0}", UnicastIPInfoCol[i].IPv4Mask); } } } } } if (!match) { Console.WriteLine("No matches found!, try again"); } }
/// <summary> /// 通过mac地址获取ip地址 /// </summary> /// <param name="mac"></param> /// <param name="getIPV6"></param> /// <returns></returns> public static IPInfo GetIpAddressByMacAddress(string mac, bool getIPV6 = false) { bool found = false; string tmpMac = mac.Replace("-", "").Replace(":", "").ToUpper().Trim(); IPInfo ipInfo = new IPInfo(); NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (found) { break; } if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet || adapter.NetworkInterfaceType == NetworkInterfaceType.Wireless80211) { string macadd = adapter.GetPhysicalAddress().ToString(); if (macadd.ToUpper().Trim().Equals(tmpMac)) { //获取以太网卡网络接口信息 IPInterfaceProperties ip = adapter.GetIPProperties(); //获取单播地址集 UnicastIPAddressInformationCollection ipCollection = ip.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { if (ipadd.Address.AddressFamily == AddressFamily.InterNetwork) { //判断是否为ipv4 ipInfo.IpV4 = ipadd.Address.ToString().Trim(); } if (getIPV6) { if (ipadd.Address.AddressFamily == AddressFamily.InterNetworkV6) { //判断是否为ipv6 ipInfo.IpV6 = ipadd.Address.ToString().Trim(); } } if (getIPV6) { if (!string.IsNullOrEmpty(ipInfo.IpV4) && !string.IsNullOrEmpty(ipInfo.IpV6)) { found = true; break; } } else { if (!string.IsNullOrEmpty(ipInfo.IpV4)) { found = true; break; } } } } } } if (found) { return(ipInfo); } return(null !); }
/// <summary> /// Preparations for monitoring. /// </summary> internal void init() { interfaceStats = nic.GetIPv4Statistics(); props = nic.GetIPProperties(); gateway = props.GatewayAddresses.Count > 0 ? props.GatewayAddresses[props.GatewayAddresses.Count - 1].Address.ToString() : " N/A "; uniCast = props.UnicastAddresses; uniIP = uniCast.Count > 0 ? uniCast[uniCast.Count - 1].Address.ToString() : " N/A "; //the last address in array should be IPv4...but not always... uniIPMask = uniCast.Count > 0 ? uniCast[uniCast.Count - 1].IPv4Mask.ToString() : " N/A "; // Since dlValueOld and ulValueOld are used in method refresh() to calculate network speed, they must have be initialized. this.dlValueOld = interfaceStats.BytesReceived; this.ulValueOld = interfaceStats.BytesSent; }
public static List <ModelNetworkCard> getNetworkInterfaceMessage() { List <ModelNetworkCard> cardInfList = new List <ModelNetworkCard>(); NetworkInterface[] fNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces(); cardInfList.Clear(); foreach (NetworkInterface adapter in fNetworkInterfaces) { #region " 网卡类型 " string fPnpInstanceID = ""; string fCardType = "未知网卡"; string fRegistryKey = "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}\\" + adapter.Id + "\\Connection"; RegistryKey rk = Registry.LocalMachine.OpenSubKey(fRegistryKey, false); if (rk != null) { // 区分 PnpInstanceID // 如果前面有 PCI 就是本机的真实网卡 // MediaSubType 为 01 则是常见网卡,02为无线网卡。 fPnpInstanceID = rk.GetValue("PnpInstanceID", "").ToString(); int fMediaSubType = Convert.ToInt32(rk.GetValue("MediaSubType", 0)); if (fPnpInstanceID.Length > 3 && fPnpInstanceID.Substring(0, 3) == "PCI") { fCardType = "物理网卡"; } else if (fMediaSubType == 1) { fCardType = "虚拟网卡"; } else if (fMediaSubType == 2) { fCardType = "无线网卡"; } ModelNetworkCard model = new ModelNetworkCard(); model.mName = adapter.Description; model.mType = fCardType; model.mInterface = (int)adapter.NetworkInterfaceType; IPInterfaceProperties fIPInterfaceProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection UnicastIPAddressInformationCollection = fIPInterfaceProperties.UnicastAddresses; foreach (UnicastIPAddressInformation UnicastIPAddressInformation in UnicastIPAddressInformationCollection) { if (UnicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork) { } Console.WriteLine("Ip Address .......... : {0}", UnicastIPAddressInformation.Address); // Ip 地址 model.mIp = String.Format("{0}", UnicastIPAddressInformation.Address); } if (adapter.OperationalStatus == OperationalStatus.Up) { model.mEnable = true; } else { model.mEnable = false; } cardInfList.Add(model); } #endregion #region " 网卡信息 " Console.WriteLine("-----------------------------------------------------------"); Console.WriteLine("-- " + fCardType); Console.WriteLine("-----------------------------------------------------------"); Console.WriteLine("Id .................. : {0}", adapter.Id); // 获取网络适配器的标识符 Console.WriteLine("Name ................ : {0}", adapter.Name); // 获取网络适配器的名称 Console.WriteLine("Description ......... : {0}", adapter.Description); // 获取接口的描述 Console.WriteLine("Interface type ...... : {0}", adapter.NetworkInterfaceType); // 获取接口类型 Console.WriteLine("Is receive only...... : {0}", adapter.IsReceiveOnly); // 获取 Boolean 值,该值指示网络接口是否设置为仅接收数据包。 Console.WriteLine("Multicast............ : {0}", adapter.SupportsMulticast); // 获取 Boolean 值,该值指示是否启用网络接口以接收多路广播数据包。 Console.WriteLine("Speed ............... : {0}", adapter.Speed); // 网络接口的速度 Console.WriteLine("Physical Address .... : {0}", adapter.GetPhysicalAddress().ToString()); // MAC 地址 Console.WriteLine("OperationalStatus ... : {0}", adapter.OperationalStatus); //当前网卡状态 } #endregion return(cardInfList); }
/// <summary> /// 获取单个适配器的信息 /// <para>所有请使用GetAdapters()</para> /// </summary> /// <param name="name">适配器的名称</param> public TSAdapter(string name) { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter"); ManagementObjectCollection wmiadps = searcher.Get(); foreach (NetworkInterface adapter in adapters) { if (adapter.Name == name) { //this.name = adapter.Name; this.description = adapter.Description; this.status = adapter.OperationalStatus; this.type = adapter.NetworkInterfaceType; IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); //IP if (uniCast.Count > 1) { if (uniCast[1].IPv4Mask != null) { this.ip = uniCast[1].Address.ToString(); this.mask = uniCast[1].IPv4Mask.ToString(); } } //网关 GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses; if (addresses.Count > 0) { this.gateway = addresses[0].Address.ToString(); } //DNS IPAddressCollection dnsServers = adapterProperties.DnsAddresses; switch (dnsServers.Count) { case 1: this.dns = new string[1]; this.dns[0] = dnsServers[0].ToString(); break; case 2: this.dns = new string[2]; this.dns[0] = dnsServers[0].ToString(); this.dns[1] = dnsServers[1].ToString(); break; } //Index if (p != null) { this.interFace = p.Index; } //WMI中的数据 foreach (ManagementObject mo in wmiadps) { if ((string)mo.GetPropertyValue("NetConnectionID") == this.name) { //服务名称 this.serviceName = (string)mo.GetPropertyValue("ServiceName"); } } break; } } }
private void InitializeIPs(NetworkLocale locale) { Cursor.Current = Cursors.WaitCursor; try { cboxIPAddress.Items.Clear(); cboxIPAddress.DropDownStyle = ComboBoxStyle.DropDownList; if (locale == NetworkLocale.Network) { _networkInfo = new NetworksAdapterInfo(); foreach (AdapterInfo info in _networkInfo.GetNetworkAdapterInformation()) { cboxIPAddress.Items.Add(info.Name + " @ " + info.IP); } cboxIPAddress.SelectedIndex = 0; lblIPAdd.Text = "Computer IP:"; lblIPAdd.ImageIndex = 9; } else if (locale == NetworkLocale.LocalIP) { NetworkInterface[] ifaceList = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface iface in ifaceList) { if (_operationalStatusOnly == true) { if (iface.OperationalStatus == OperationalStatus.Up) { UnicastIPAddressInformationCollection unicastIPC = iface.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation unicast in unicastIPC) { if (unicast.Address.AddressFamily == AddressFamily.InterNetwork) { cboxIPAddress.Items.Add(iface.Description + " @ " + unicast.Address); } } } } else { UnicastIPAddressInformationCollection unicastIPC = iface.GetIPProperties().UnicastAddresses; foreach (UnicastIPAddressInformation unicast in unicastIPC) { if (unicast.Address.AddressFamily == AddressFamily.InterNetwork) { cboxIPAddress.Items.Add(iface.Description + " @ " + unicast.Address); } } } } cboxIPAddress.SelectedIndex = 0; lblIPAdd.Text = " Network Card IP:"; lblIPAdd.ImageIndex = 3; } else if (locale == NetworkLocale.LocalGUID) { _networkInfo = new NetworksAdapterInfo(); foreach (AdapterInfo info in _networkInfo.GetNetworkGUIDInformation()) { cboxIPAddress.Items.Add(info.Name + " @ " + info.IP); } cboxIPAddress.SelectedIndex = 0; lblIPAdd.Text = " Network Card GUID:"; lblIPAdd.ImageIndex = 3; } else { cboxIPAddress.DropDownStyle = ComboBoxStyle.Simple; lblIPAdd.Text = " Enter IP Address:"; lblIPAdd.ImageIndex = 6; } } catch { } finally { Cursor.Current = Cursors.Default; } }
/// <summary> /// 获取所有适配器的状态、属性 /// </summary> /// <returns>每个适配器的泛型</returns> public static List <TSAdapter> GetAdapters() { List <TSAdapter> back = new List <TSAdapter>(); NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter"); ManagementObjectCollection wmiadps = searcher.Get(); foreach (NetworkInterface adapter in adapters) { TSAdapter adp = new TSAdapter(); adp.name = adapter.Name; adp.description = adapter.Description; adp.status = adapter.OperationalStatus; adp.type = adapter.NetworkInterfaceType; IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; IPv4InterfaceProperties p; try { p = adapterProperties.GetIPv4Properties(); } catch { p = null; } //IP if (uniCast.Count > 1) { if (uniCast[1].IPv4Mask != null) { adp.ip = uniCast[1].Address.ToString(); adp.mask = uniCast[1].IPv4Mask.ToString(); } } //网关 GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses; if (addresses.Count > 0) { adp.gateway = addresses[0].Address.ToString(); } //DNS IPAddressCollection dnsServers = adapterProperties.DnsAddresses; switch (dnsServers.Count) { case 1: adp.dns = new string[1]; adp.dns[0] = dnsServers[0].ToString(); break; case 2: adp.dns = new string[2]; adp.dns[0] = dnsServers[0].ToString(); adp.dns[1] = dnsServers[1].ToString(); break; } //Index if (p != null) { adp.interFace = p.Index; } //WMI中的数据 foreach (ManagementObject mo in wmiadps) { if ((string)mo.GetPropertyValue("NetConnectionID") == adp.name) { //服务名称 adp.serviceName = (string)mo.GetPropertyValue("ServiceName"); //GUID adp.guid = (string)mo.GetPropertyValue("GUID"); } } //是否为自动DNS RegistryKey r1 = Registry.LocalMachine; RegistryKey r2 = r1.OpenSubKey(@"SYSTEM\ControlSet001\Services\Tcpip\Parameters\Interfaces\" + adp.guid); string t = (string)r2.GetValue("NameServer"); if (t == "") { adp.isAutoDns = true; } else { adp.isAutoDns = false; } back.Add(adp); } return(back); }
public static IServiceHostBuilder UseServer(this IServiceHostBuilder hostBuilder, string ip, int port, string token = "True") { return(hostBuilder.MapServices(mapper => { BuildServiceEngine(mapper); mapper.Resolve <IServiceCommandManager>().SetServiceCommandsAsync(); var serviceEntryManager = mapper.Resolve <IServiceEntryManager>(); string serviceToken = mapper.Resolve <IServiceTokenGenerator>().GeneratorToken(token); int _port = AppConfig.ServerOptions.Port == 0? port: AppConfig.ServerOptions.Port; string _ip = AppConfig.ServerOptions.Ip ?? ip; _port = AppConfig.ServerOptions.IpEndpoint?.Port ?? _port; _ip = AppConfig.ServerOptions.IpEndpoint?.Address.ToString() ?? _ip; if (_ip.IndexOf(".") < 0 || _ip == "" || _ip == "0.0.0.0") { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in nics) { if (adapter.NetworkInterfaceType == NetworkInterfaceType.Ethernet && (_ip == "" || _ip == "0.0.0.0" || _ip == adapter.Name)) { IPInterfaceProperties ipxx = adapter.GetIPProperties(); UnicastIPAddressInformationCollection ipCollection = ipxx.UnicastAddresses; foreach (UnicastIPAddressInformation ipadd in ipCollection) { if (ipadd.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { _ip = ipadd.Address.ToString(); } } } } } var mappingIp = AppConfig.ServerOptions.MappingIP ?? _ip; var mappingPort = AppConfig.ServerOptions.MappingPort; if (mappingPort == 0) { mappingPort = _port; } new ServiceRouteWatch(mapper.Resolve <CPlatformContainer>(), () => { var addressDescriptors = serviceEntryManager.GetEntries().Select(i => new ServiceRoute { Address = new[] { new IpAddressModel { Ip = mappingIp, Port = mappingPort, ProcessorTime = Math.Round(Convert.ToDecimal(Process.GetCurrentProcess().TotalProcessorTime.TotalSeconds), 2, MidpointRounding.AwayFromZero), Token = serviceToken } }, ServiceDescriptor = i.Descriptor }).ToList(); mapper.Resolve <IServiceRouteManager>().SetRoutesAsync(addressDescriptors); }); mapper.Resolve <IModuleProvider>().Initialize(); var serviceHost = mapper.Resolve <Runtime.Server.IServiceHost>(); Task.Factory.StartNew(async() => { await serviceHost.StartAsync(new IPEndPoint(IPAddress.Parse(_ip), _port)); }).Wait(); })); }
private UnicastIPAddressInformationCollection GetUnicastAddresses() { UnicastIPAddressInformationCollection collection = new UnicastIPAddressInformationCollection(); foreach (UnicastIPAddressInformation info in LinuxNetworkInterface.GetLinuxNetworkInterfaces().SelectMany(lni => lni.GetIPProperties().UnicastAddresses)) { // PERF: Use Interop.Sys.EnumerateInterfaceAddresses directly here. collection.InternalAdd(info); } return collection; }
/// <summary> /// 刷新适配器状态 /// </summary> public void Fresh() { NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapter"); ManagementObjectCollection wmiadps = searcher.Get(); foreach (NetworkInterface adapter in adapters) { if (adapter.Name == name) { status = adapter.OperationalStatus; type = adapter.NetworkInterfaceType; IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; IPv4InterfaceProperties p = adapterProperties.GetIPv4Properties(); //IP if (uniCast.Count > 1) { if (uniCast[1].IPv4Mask != null) { ip = uniCast[1].Address.ToString(); mask = uniCast[1].IPv4Mask.ToString(); } } //网关 GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses; if (addresses.Count > 0) { gateway = addresses[0].Address.ToString(); } //DNS IPAddressCollection dnsServers = adapterProperties.DnsAddresses; switch (dnsServers.Count) { case 1: dns = new string[1]; dns[0] = dnsServers[0].ToString(); break; case 2: dns = new string[2]; dns[0] = dnsServers[0].ToString(); dns[1] = dnsServers[1].ToString(); break; } //Index if (p != null) { interFace = p.Index; } //WMI中的数据 foreach (ManagementObject mo in wmiadps) { if ((string)mo.GetPropertyValue("NetConnectionID") == name) { //服务名称 serviceName = (string)mo.GetPropertyValue("ServiceName"); } } //是否为自动DNS RegistryKey r1 = Registry.LocalMachine; RegistryKey r2 = r1.OpenSubKey(@"SYSTEM\ControlSet001\Services\Tcpip\Parameters\Interfaces\" + guid); string t = (string)r2.GetValue("NameServer"); if (t == "") { isAutoDns = true; } else { isAutoDns = false; } break; } } }
public static IUnicastIPAddressInformationCollection ToInterface([CanBeNull] this UnicastIPAddressInformationCollection collection) { return((collection == null) ? null : new UnicastIpAddressInformationCollectionAdapter(collection)); }
// Helper method that marshals the address information into the classes. internal static UnicastIPAddressInformationCollection MarshalUnicastIpAddressInformationCollection(IntPtr ptr) { UnicastIPAddressInformationCollection addressList = new UnicastIPAddressInformationCollection(); while (ptr != IntPtr.Zero) { Interop.IpHlpApi.IpAdapterUnicastAddress addr = Marshal.PtrToStructure<Interop.IpHlpApi.IpAdapterUnicastAddress>(ptr); addressList.InternalAdd(new SystemUnicastIPAddressInformation(addr)); ptr = addr.next; } return addressList; }
//读取给定的网卡信息 private void showAdapterIPInfo(NetworkInterface adapter) { clearTextbox(); IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); UnicastIPAddressInformationCollection ipCollection = adapterProperties.UnicastAddresses; GatewayIPAddressInformationCollection gatewayColletion = adapterProperties.GatewayAddresses; //MessageBox.Show(adapter.Id); foreach (var item in ipCollection) { if (item.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { if (item.Address.ToString().Substring(0, 7) == "169.254") { try { string[] temp = (string[])regInterface.OpenSubKey(adapter.Id, true).GetValue("IPAddress"); ipAddressTextbox.Text = temp[0]; } catch { ipAddressTextbox.Text = ""; } } else { ipAddressTextbox.Text = item.Address.ToString(); } try { submaskTextBox.Text = item.IPv4Mask.ToString(); //submaskTextBox.Text = item.IPv4Mask.ToString(); } catch { try { string[] temp = (string[])regInterface.OpenSubKey(adapter.Id, true).GetValue("SubnetMask"); submaskTextBox.Text = temp[0]; } catch { submaskTextBox.Text = ""; } //MessageBox.Show("没有连接网络,本程序可能不能正常使用,请连接网络后重启启动本程序"); //Application.Exit(); } } } foreach (var item in gatewayColletion) { ipGatewayTextbox.Text = item.Address.ToString(); } IPAddressCollection dnss = adapterProperties.DnsAddresses; //TextBox[] dnsArr; List <TextBox> dnsList = new List <TextBox>(new TextBox[] { dns1TextBox, dns2TextBox, dns3TextBox, dns4TextBox }); //int i = 0; foreach (IPAddress dns in dnss) { foreach (TextBox d in dnsList) { if (d.TextLength == 0) { d.Text = dns.ToString(); break; } } } }
static UnicastIPAddressInformationCollection Win32FromUnicast (int ifIndex, IntPtr ptr) { UnicastIPAddressInformationCollection c = new UnicastIPAddressInformationCollection (); Win32_IP_ADAPTER_UNICAST_ADDRESS a; for (IntPtr p = ptr; p != IntPtr.Zero; p = a.Next) { a = (Win32_IP_ADAPTER_UNICAST_ADDRESS) Marshal.PtrToStructure (p, typeof (Win32_IP_ADAPTER_UNICAST_ADDRESS)); c.Add (new Win32UnicastIPAddressInformation (ifIndex, a)); } return c; }
public static void GetIPv4gateway(IP_ADAPTER_ADDRESSES A, IPAddress ipaddr, out int bc, out string ba) { bc = 32; ba = ""; string first_multi = ""; Trace.WriteLine("start GetIPv4gateway"); NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces(); foreach (NetworkInterface adapter in adapters) { // match c# adapter to win32 adapter A passed in if (adapter.Name.CompareTo(Marshal.PtrToStringAuto(A.FriendlyName)) != 0) { continue; } // get a c# view of adapter properties IPInterfaceProperties adapterProperties = adapter.GetIPProperties(); // get the first multicast address MulticastIPAddressInformationCollection multiCast = adapterProperties.MulticastAddresses; if (multiCast != null) { foreach (IPAddressInformation multi in multiCast) { if (first_multi.Length == 0) { multi.Address.ToString(); } Trace.WriteLine(" multi " + multi.Address.ToString()); continue; } } UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses; if (uniCast != null) { foreach (UnicastIPAddressInformation uni in uniCast) { // chop off any % char and what trails it string s1 = uni.Address.ToString(); string s2 = ipaddr.ToString(); if (s1.IndexOf((char)'%') != -1) { s1 = s1.Substring(0, s1.IndexOf((char)'%')); } if (s2.IndexOf((char)'%') != -1) { s2 = s2.Substring(0, s2.IndexOf((char)'%')); } if (s1.Equals(s2)) { Trace.WriteLine("unicast addr " + s1); if (uni.IPv4Mask != null) { byte[] bcast_add = uni.Address.GetAddressBytes(); // check for ipv4 if (uni.IPv4Mask.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) { ba = uni.IPv4Mask.ToString(); byte[] ipAdressBytes = uni.Address.GetAddressBytes(); byte[] subnetMaskBytes = uni.IPv4Mask.GetAddressBytes(); if (ipAdressBytes.Length != subnetMaskBytes.Length) { if (ipAdressBytes.Length > 4) { Trace.WriteLine(" ipAdressBytes.Length = " + ipAdressBytes.Length.ToString()); Trace.WriteLine(" different addr length " + uni.Address.ToString() + " " + uni.IPv4Mask.ToString()); ba = first_multi; bc = 64; } break; } bc = 0; int totbits = subnetMaskBytes.Length * 8; for (int i = 0; i < subnetMaskBytes.Length; i++) { for (int j = 0; j < totbits; j++) { byte maskbit = (byte)(1 << j); if ((maskbit & subnetMaskBytes[i]) != 0) { bc++; } else { bcast_add[i] |= maskbit; } } } StringBuilder sb = new StringBuilder(bcast_add.Length * 4); foreach (byte b in bcast_add) { sb.AppendFormat("{0}", b); sb.Append("."); } sb.Remove(sb.Length - 1, 1); ba = sb.ToString(); } } else { ba = first_multi; if (A.IfType == 24) { // loopback bc = 8; } else { bc = 32; } break; } } } } /* the code below doesn't display any gateways on win7, seems like it should * if (System.Environment.OSVersion.Version.Major >= 6) //vista or later * { * Trace.WriteLine("Gateways"); * GatewayIPAddressInformationCollection addresses = adapterProperties.GatewayAddresses; * if (addresses.Count > 0) * { * Trace.WriteLine(adapter.Description); * foreach (GatewayIPAddressInformation address in addresses) * { * Trace.WriteLine(" Gateway Address : {0}", * address.Address.ToString()); * } * } * } */ break; } Trace.WriteLine("end GetIPv4gateway"); }