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);
     }
 }
示例#2
0
        public Page2()
        {
            InitializeComponent();
            StringBuilder sb = new StringBuilder();

            NetworkInterface[] adpters = NetworkInterface.GetAllNetworkInterfaces();
            sb.AppendLine("适配器个数:" + adpters.Length);
            int kase = 0;

            foreach (NetworkInterface adpter in adpters)
            {
                kase++;
                sb.AppendLine("-----------第" + kase + "个适配器信息------------");
                sb.AppendLine("描述信息:" + adpter.Description);
                sb.AppendLine("名称:" + adpter.Name);
                sb.AppendLine("速度:" + adpter.Speed / 1000 / 1000 + "M");
                byte[] macBytes = adpter.GetPhysicalAddress().GetAddressBytes();
                sb.AppendLine("MAC地址:" + BitConverter.ToString(macBytes));
                IPInterfaceProperties ipp        = adpter.GetIPProperties();
                IPAddressCollection   dnsservers = ipp.DnsAddresses;
                if (dnsservers.Count > 0)
                {
                    foreach (IPAddress dns in dnsservers)
                    {
                        sb.AppendLine("DNS服务器IP地址:" + dns);
                    }
                }
            }
            text1.Text = sb.ToString();
        }
示例#3
0
        private static IPAddress GetDnsAddress()
        {
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (System.Net.NetworkInformation.NetworkInterface networkInterface in networkInterfaces)
            {
                if (networkInterface.OperationalStatus == OperationalStatus.Up)
                {
                    IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                    IPAddressCollection   dnsAddresses = ipProperties.DnsAddresses;
                    foreach (IPAddress dnsAddress in dnsAddresses)
                    {
                        return(dnsAddress);
                    }
                }
            }

            // alternative
            string linuxResolveFilename = "/etc/resolv.conf";

            if (File.Exists(linuxResolveFilename))
            {
                string[] lines = File.ReadAllLines(linuxResolveFilename);
                foreach (string line in lines)
                {
                    Match nameserverMatch = Regex.Match(line, "nameserver\\s+([0-9]+)\\.([0-9]+)\\.([0-9]+)\\.([0-9]+)", RegexOptions.Compiled);
                    if (nameserverMatch.Success)
                    {
                        return(IPAddress.Parse(nameserverMatch.Groups[1].Value + "." + nameserverMatch.Groups[2].Value + "." + nameserverMatch.Groups[3].Value + "." + nameserverMatch.Groups[4].Value));
                    }
                }
            }

            return(null);
        }
示例#4
0
文件: Program.cs 项目: zedoax/dig
        /// <summary>
        /// Iterate Current DNS Servers to Find Working One
        /// </summary>
        public static IPAddress GetDefaultDns()
        {
            {
                NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

                foreach (NetworkInterface networkInterface in networkInterfaces)
                {
                    if (networkInterface.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                        IPAddressCollection   dnsAddresses = ipProperties.DnsAddresses;

                        foreach (IPAddress dnsAdress in dnsAddresses)
                        {
                            try
                            {
                                // Test Connection and Return
                                var conn = new UdpClient();
                                conn.Connect(dnsAdress, 53);
                                conn.Close();
                                return(dnsAdress);
                            } catch {}
                            // Check Next One
                        }
                    }
                }

                // Print Error If Unable to Find Default DNS
                Console.Error.WriteLine("Unable to Locate DNS Server");
                return(null);
            }
        }
示例#5
0
        private void ShowAdapterInfo()
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            listBox1.Items.Add("适配器个数: " + adapters.Length);
            int index = 0;

            foreach (NetworkInterface adapter in adapters)
            {
                index++;
                //显示网络适配器描述的信息。名称。类型。速度。mac
                listBox1.Items.Add("描述信息:{0}" + adapter.Description);
                listBox1.Items.Add("名称:{0}" + adapter.Name);
                listBox1.Items.Add("类型:{0}" + adapter.NetworkInterfaceType);
                listBox1.Items.Add("速度:{0}" + adapter.Speed);
                listBox1.Items.Add("Mac:{0}" + adapter.GetPhysicalAddress());
                //获取ipinterfaceproperties实例
                IPInterfaceProperties adapterproperties = adapter.GetIPProperties();
                //获取dns ip
                IPAddressCollection dnsservers = adapterproperties.DnsAddresses;
                if (dnsservers.Count > 0)
                {
                    foreach (IPAddress dns in dnsservers)
                    {
                        listBox1.Items.Add("DNS:{0}" + dns + "\n");
                    }
                }
                else
                {
                    listBox1.Items.Add("DNS:{0}" + "空" + "\n");
                }
            }
        }
示例#6
0
        public void Test_ipv6_CountIPAddress() {

            IPNetwork ipn = IPNetwork.Parse("::/125");
            using (IPAddressCollection ips = ipn.ListIPAddress()) {
                Assert.AreEqual(8, ips.Count, "Count");
            }
        }
示例#7
0
        string getDNS()
        {
            NetworkInterface[]    interfaces = NetworkInterface.GetAllNetworkInterfaces();
            string                dnsServers = "";
            IPInterfaceProperties ipProps    = null;

            foreach (NetworkInterface nic in interfaces)
            {
                if (nic.OperationalStatus == OperationalStatus.Up)
                {
                    ipProps = nic.GetIPProperties();
                    break;
                }
            }
            IPAddressCollection dnsAddr = ipProps.DnsAddresses;
            int numDNS = dnsAddr.Count;
            int i      = 0;

            while (i < numDNS - 1)
            {
                IPAddress addr = dnsAddr[i];
                dnsServers = dnsServers + addr.ToString() + ", ";
                i++;
            }
            dnsServers = dnsServers + dnsAddr[i].ToString();
            return(dnsServers);
        }
示例#8
0
 private static void ShowIPAddressCollection(IPAddressCollection collection)
 {
     for (var i = 0; i < collection.Count; i++)
     {
         Console.WriteLine("                                   :" + GetIPAddressInfo(collection[i]));
     }
 }
示例#9
0
        public string DisplayDHCPServerAddresses()
        {
            // empty string to store DHCP address
            string dhcpServerAddress = null;

            dhcpServerAddress = "DHCP Servers";
            // array of adapters
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();

            // loop through the array and get all adapters
            foreach (NetworkInterface adapter in adapters)
            {
                // get property of adapters
                IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
                // get DHCP address of the adapters
                IPAddressCollection addresses = adapterProperties.DhcpServerAddresses;
                if (addresses.Count > 0)
                {
                    // print out the name of the Adapter
                    dhcpServerAddress = dhcpServerAddress + "\n" + adapter.Description;
                    foreach (IPAddress address in addresses)
                    {
                        // Loop through the DHCP addresses of the adapters
                        dhcpServerAddress = dhcpServerAddress + $"\nDHCP Address : {address.ToString()}";
                    }

                    Console.WriteLine();
                }
            }
            // return with adapter names, and their DHCP server ip address.
            return(dhcpServerAddress);
        }
 internal SystemIPv4InterfaceProperties(FixedInfo fixedInfo, IpAdapterInfo ipAdapterInfo)
 {
     this.index = ipAdapterInfo.index;
     this.routingEnabled = fixedInfo.EnableRouting;
     this.dhcpEnabled = ipAdapterInfo.dhcpEnabled;
     this.haveWins = ipAdapterInfo.haveWins;
     this.gatewayAddresses = ipAdapterInfo.gatewayList.ToIPGatewayAddressCollection();
     this.dhcpAddresses = ipAdapterInfo.dhcpServer.ToIPAddressCollection();
     IPAddressCollection addresss = ipAdapterInfo.primaryWinsServer.ToIPAddressCollection();
     IPAddressCollection addresss2 = ipAdapterInfo.secondaryWinsServer.ToIPAddressCollection();
     this.winsServerAddresses = new IPAddressCollection();
     foreach (IPAddress address in addresss)
     {
         this.winsServerAddresses.InternalAdd(address);
     }
     foreach (IPAddress address2 in addresss2)
     {
         this.winsServerAddresses.InternalAdd(address2);
     }
     SystemIPv4InterfaceStatistics statistics = new SystemIPv4InterfaceStatistics((long) this.index);
     this.mtu = (uint) statistics.Mtu;
     if (ComNetOS.IsWin2K)
     {
         this.GetPerAdapterInfo(ipAdapterInfo.index);
     }
     else
     {
         this.dnsAddresses = fixedInfo.DnsAddresses;
     }
 }
 internal static GatewayIPAddressInformationCollection ToGatewayIpAddressInformationCollection(IPAddressCollection addresses) {
     GatewayIPAddressInformationCollection gatewayList = new GatewayIPAddressInformationCollection();
     foreach (IPAddress address in addresses) {
         gatewayList.InternalAdd(new SystemGatewayIPAddressInformation(address));
     }
     return gatewayList;
 }
示例#12
0
        public static void Main(string[] args)
        {
            string target   = args[0];
            string username = args[1];
            string hash     = args[2];
            // Parse CIDR
            IPNetwork           ipn = IPNetwork.Parse(target);
            IPAddressCollection ips = IPNetwork.ListIPAddress(ipn);

            // Parallel ForEach to iterate over IP's from CIDR block
            Parallel.ForEach(ips, (ip) =>
            {
                try
                {
                    string[] arguments;
                    string targetIP = ip.ToString();
                    arguments       = new string[3] {
                        targetIP, username, hash
                    };
                    SharpInvoke_SMBExec.Program.Main(arguments);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            });
        }
        // 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);
            }
        }
示例#14
0
        /// <summary>
        /// Prints a list of adapters and their DNS Server IP Addresses (for IPv4 addresses)
        /// </summary>
        /// <param name="bolNewLine">
        /// (Optional, Default TRUE) whether to write to a new line after printing
        /// information.
        /// </param>
        public static void GetDNSAddresses_IPv4(bool bolNewLine = true)
        {
            NetworkInterface[] localNetAdapters = NetworkInterface.GetAllNetworkInterfaces(); // Get list of local adapters

            System.Console.ForegroundColor = ConsoleColor.White;
            System.Console.WriteLine("DNS Servers.....................");
            System.Console.ForegroundColor = clsConsole.color;

            foreach (NetworkInterface adapter in localNetAdapters)
            {
                IPInterfaceProperties adapterProperties = adapter.GetIPProperties();      // Get adapter IP properties
                IPAddressCollection   adapterDNSServers = adapterProperties.DnsAddresses; // Get DNS IP Information

                if (adapterDNSServers.Count > 0)                                          // If the adapter has a DNS address
                {
                    foreach (IPAddress adapterDNS in adapterDNSServers)
                    {
                        if (adapterDNS.AddressFamily.ToString().Equals("InterNetwork")) // Catch IPv4 Addresses
                        {
                            System.Console.Write(adapter.Name);

                            System.Console.ForegroundColor = ConsoleColor.DarkGray;

                            clsGeneral.CreateConsoleBuffer(32, adapter.Name.ToString().Length, Console.CursorTop); // Set Buffer

                            System.Console.WriteLine(adapterDNS.ToString());
                        }

                        System.Console.ForegroundColor = clsConsole.color;
                    }
                }
            }

            clsNetwork.InsertNewLine(bolNewLine);
        }
示例#15
0
        public static Boolean IsSafe(Boolean showDebugMessage)
        {
            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface networkInterface in networkInterfaces)
            {
                if (networkInterface.NetworkInterfaceType == NetworkInterfaceType.Ethernet || networkInterface.NetworkInterfaceType == NetworkInterfaceType.Wireless80211)
                {
                    if (networkInterface.OperationalStatus == OperationalStatus.Up)
                    {
                        IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                        IPAddressCollection   dnsAddresses = ipProperties.DnsAddresses;

                        foreach (IPAddress dnsAddress in dnsAddresses)
                        {
                            if (dnsAddress.MapToIPv4().ToString() != PREFERRED_SAFE_DNS && dnsAddress.MapToIPv4().ToString() != ALTERNATE_SAFE_DNS)
                            {
                                if (showDebugMessage)
                                {
                                    System.Windows.Forms.MessageBox.Show(networkInterface.Name + "   " + networkInterface.NetworkInterfaceType + "     " + dnsAddress.ToString());
                                }
                                return(false);
                            }
                        }
                    }
                }
            }
            return(true);
        }
示例#16
0
        public void TestReset() {

            IPNetwork ipn = IPNetwork.Parse("192.168.1.0/29");
            using (IPAddressCollection ips = ipn.ListIPAddress()) {
                ips.Reset();
            }
        }
示例#17
0
        /// <summary>
        /// 显示网卡信息
        /// </summary>
        private void ShowAdapterInfo()
        {
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            listBoxAdpterInfo.Items.Add("适配器个数:" + adapters.Length);
            int index = 0;

            foreach (NetworkInterface adapter in adapters)
            {
                index++;
                //显示网络适配器描述信息、名称、型号、速度、MAC地址
                listBoxAdpterInfo.Items.Add("-----------------第" + index + "个适配器信息-------------------");
                listBoxAdpterInfo.Items.Add("描述信息:{0}" + adapter.Description);
                listBoxAdpterInfo.Items.Add("名称:{0}" + adapter.Name);
                listBoxAdpterInfo.Items.Add("类型:{0}" + adapter.NetworkInterfaceType);
                listBoxAdpterInfo.Items.Add("速度:{0}" + adapter.Speed);
                listBoxAdpterInfo.Items.Add("MAC地址:{0}" + adapter.GetPhysicalAddress());

                //获取IPInterfaceProperties实例
                IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
                //获取并显示DNS服务器IP地址信息
                IPAddressCollection dnsServers = adapterProperties.DnsAddresses;
                if (dnsServers.Count > 0)
                {
                    foreach (IPAddress dns in dnsServers)
                    {
                        listBoxAdpterInfo.Items.Add("DNS服务器IP地址:{0} " + dns + "\n");
                    }
                }
                else
                {
                    listBoxAdpterInfo.Items.Add("DNS服务器IP地址:{0} " + "\n");
                }
            }
        }
示例#18
0
        /// <summary>
        /// Get all the ip addresses for the different network interfaces
        /// </summary>
        /// <returns></returns>
        public IPAddress[] GetAllDhcpServers()
        {
            List <IPAddress> dhcpadresses = new List <IPAddress>();

            try
            {
                NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
                foreach (NetworkInterface adapter in adapters)
                {
                    IPInterfaceProperties adapteradapterProperties = adapter.GetIPProperties();
                    IPAddressCollection   addresses = adapteradapterProperties.DhcpServerAddresses;

                    for (int i = 0; i < addresses.Count; i++)
                    {
                        dhcpadresses.Add(addresses[i]);
                    }
                }
            }
            catch (Exception e)
            {
                throw e;
            }

            return(dhcpadresses.ToArray());
        }
示例#19
0
        private static void GetExistingDNS(NetworkInterface Nic)
        {
            _ = new string[2];
            int i = 0;
            IPInterfaceProperties adapterProperties = Nic.GetIPProperties();
            IPAddressCollection   dnsServers        = adapterProperties.DnsAddresses;

            if (dnsServers.Count > 0)
            {
                foreach (IPAddress dns in dnsServers)
                {
                    if (dns.ToString() != "127.0.0.1")
                    {
                        if (i == 0)
                        {
                            Properties.Settings.Default.DNS1 = dns.ToString();
                        }
                        if (i == 1)
                        {
                            Properties.Settings.Default.DNS2 = dns.ToString();
                        }
                    }
                    else
                    {
                        Network_loop = true;
                    }

                    i++;
                }
                Properties.Settings.Default.Save();
            }
        }
示例#20
0
        public VLan(string cidr)
        {
            Cidr       = cidr;
            _ipnetwork = IPNetwork.Parse(Cidr);

            _ipAddresses = _ipnetwork.ListIPAddress(FilterEnum.Usable);
        }
        private static string FormatIPAddressList(IPAddressCollection addressCollection)
        {
            if (addressCollection == null)
            {
                return("NONE");
            }

            if (addressCollection.Count == 0)
            {
                return("NONE");
            }

            string addresses = string.Empty;

            foreach (IPAddress ipAddress in addressCollection)
            {
                if (string.IsNullOrEmpty(addresses))
                {
                    addresses = ipAddress.ToString();
                }
                else
                {
                    addresses += ", " + ipAddress;
                }
            }

            return(addresses);
        }
示例#22
0
        public DnsQueryResponse Resolve(string host, NsType queryType, NsClass queryClass, ProtocolType protocol, TsigMessageSecurityProvider provider)
        {
            string dnsServer = string.Empty;

            // Test for Unix/Linux OS
            if (Tools.IsPlatformLinuxUnix())
            {
                dnsServer = Tools.DiscoverUnixDnsServerAddress();
            }
            else
            {
                IPAddressCollection dnsServerCollection = Tools.DiscoverDnsServerAddresses();
                if (dnsServerCollection.Count == 0)
                {
                    throw new Exception("Couldn't detect local DNS Server.");
                }

                dnsServer = dnsServerCollection[0].ToString();
            }

            if (String.IsNullOrEmpty(dnsServer))
            {
                throw new Exception("Couldn't detect local DNS Server.");
            }

            return(Resolve(dnsServer, host, queryType, queryClass, protocol, provider));
        }
示例#23
0
        public void TestCountIPAddress() {

            IPNetwork ipn = IPNetwork.Parse("192.168.1.0/29");
            using (IPAddressCollection ips = ipn.ListIPAddress()) {
                Assert.AreEqual(8, ips.Count, "Count");
            }
        }
示例#24
0
        public void DisplayDnsAddresses()
        {
            strRoutine = this.Name + "; " + MethodBase.GetCurrentMethod().Name + "; ";
            try
            {
                System.Net.NetworkInformation.NetworkInterface[] adapters = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
                foreach (System.Net.NetworkInformation.NetworkInterface adapter in adapters)
                {
                    IPInterfaceProperties adapterProperties = adapter.GetIPProperties();
                    IPAddressCollection   dnsServers        = adapterProperties.DnsAddresses;

                    if (dnsServers.Count > 0)
                    {
                        Console.WriteLine(adapter.Description);
                        foreach (System.Net.IPAddress dns in dnsServers)
                        {
                            Console.WriteLine("  DNS Servers ............................. : {0}",
                                              dns.ToString());
                            //textBox1.Text = textBox1.Text + Environment.NewLine +
                            //    dns.ToString();
                        }
                        Console.WriteLine();
                    }
                }
            }
            catch (Exception ex)
            {
                csLog.LogError(strRoutine + ex.Message);
            }
        }
示例#25
0
文件: Tools.cs 项目: Kim-SSi/DnDns
        public static IPAddressCollection DiscoverDnsServerAddresses()
        {
            NetworkInterface[] arrNetworkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface objNetworkInterface in arrNetworkInterfaces)
            {
                if (
                    (objNetworkInterface.OperationalStatus == OperationalStatus.Up) &&
                    (objNetworkInterface.Speed > 0) &&
                    (objNetworkInterface.NetworkInterfaceType != NetworkInterfaceType.Loopback) &&
                    (objNetworkInterface.NetworkInterfaceType != NetworkInterfaceType.Tunnel)
                    )
                {
                    IPAddressCollection candidate = objNetworkInterface.GetIPProperties().DnsAddresses;
                    bool found = false;
                    foreach (IPAddress addr in candidate)
                    {
                        // Make this collection contains IPv4 addresses only
                        if (addr.AddressFamily == AddressFamily.InterNetwork)
                        {
                            found = true;
                        }
                    }

                    if (found)
                    {
                        return(candidate);
                    }
                }
            }

            return(null);
        }
示例#26
0
        public static int DownloadFiles(params string[] args)
        {
            WriteErrorLine("Network interfaces:");
            NetworkInterface[] interfaces = NetworkInterface.GetAllNetworkInterfaces();
            foreach (var networkInterface in interfaces)
            {
                if (networkInterface.OperationalStatus != OperationalStatus.Up)
                {
                    continue;
                }

                WriteLine("\t{0}\t\"{1}\"\t\"{2}\"", networkInterface.NetworkInterfaceType, networkInterface.Name, networkInterface.Description);
                IPInterfaceProperties ipProperties = networkInterface.GetIPProperties();
                IPAddressCollection   dnsAddresses = ipProperties.DnsAddresses;

                foreach (IPAddress dnsAddress in dnsAddresses)
                {
                    WriteLine("\t\tDNS address {0}", dnsAddress);
                }
            }

            List <Task> tasks = new List <Task>();

            for (int i = 0; i < args.Length / 2; i++)
            {
                tasks.Add(DownloadFile(args[i * 2], args[i * 2 + 1], 300, TimeSpan.FromSeconds(10)));
            }

            Task.WhenAll(tasks).Wait();
            return(0);
        }
示例#27
0
		void ParseRouteInfo (string iface)
		{
			try {
				gateways = new IPAddressCollection ();
				using (StreamReader reader = new StreamReader ("/proc/net/route")) {
					string line;
					reader.ReadLine (); // Ignore first line
					while ((line = reader.ReadLine ()) != null) {
						line = line.Trim ();
						if (line.Length == 0)
							continue;

						string [] parts = line.Split ('\t');
						if (parts.Length < 3)
							continue;
						string gw_address = parts [2].Trim ();
						byte [] ipbytes = new byte [4];  
						if (gw_address.Length == 8 && iface.Equals (parts [0], StringComparison.OrdinalIgnoreCase)) {
							for (int i = 0; i < 4; i++) {
								if (!Byte.TryParse (gw_address.Substring (i * 2, 2), NumberStyles.HexNumber, null, out ipbytes [3 - i]))
									continue;
							}
							IPAddress ip = new IPAddress (ipbytes);
							if (!ip.Equals (IPAddress.Any))
								gateways.Add (ip);
						}
					}
				}
			} catch {
			}
		}
    static void SetNICs(IP_CHOICES Choice)
    {
        NetworkInterface[] NICs = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface NIC in NICs)
        {
            // Only full NICs we care about
            if (!IsReceiveOnly(NIC))
            {
                IPInterfaceProperties IPProps   = NIC.GetIPProperties();
                IPAddressCollection   ipCollDNS = IPProps.DnsAddresses;

                foreach (IPAddress Addr in ipCollDNS)
                {
                    switch (Choice)
                    {
                    case IP_CHOICES.DEFAULT:
                        SetDNSDefault(NIC);
                        break;

                    case IP_CHOICES.LOCALHOST:
                        SetDNSProxy(NIC);
                        break;

                    case IP_CHOICES.OPENDNS:
                        SetDNSOpenDNS(NIC);
                        break;

                    case IP_CHOICES.FORCE_AUTO:
                        ForceDNSDefault(NIC);
                        break;
                    }
                }
            }
        }
    }
示例#29
0
文件: Net.cs 项目: Deleeete/Gleee
        public static string GetInfoString(this IPInterfaceProperties adapterProperties)
        {
            string re = "";
            IPAddressCollection dnsServers = adapterProperties.DnsAddresses;

            if (dnsServers != null)
            {
                re += "DNS服务器:";
                foreach (IPAddress dns in dnsServers)
                {
                    re += $"{dns}\n";
                }
                re += "\n";
            }
            IPAddressInformationCollection anyCast = adapterProperties.AnycastAddresses;

            if (anyCast != null)
            {
                re += "任播地址:";
                foreach (IPAddressInformation any in anyCast)
                {
                    re += $"{any.Address}\n";
                }
                re += "\n";
            }
            MulticastIPAddressInformationCollection multiCast = adapterProperties.MulticastAddresses;

            if (multiCast != null)
            {
                re += "组播地址:";
                foreach (IPAddressInformation multi in multiCast)
                {
                    re += $"{multi.Address}\n";
                }
                re += "\n";
            }
            UnicastIPAddressInformationCollection uniCast = adapterProperties.UnicastAddresses;

            if (uniCast != null)
            {
                string lifeTimeFormat = "dddd, MMMM dd, yyyy  hh:mm:ss tt";
                foreach (UnicastIPAddressInformation uni in uniCast)
                {
                    DateTime time;
                    re  += "单播地址:";
                    re  += $"{uni.Address}\n";
                    re  += $"\t前缀来源:\t{uni.PrefixOrigin}\n";
                    re  += $"\t后缀来源:\t{uni.SuffixOrigin}\n";
                    re  += $"\t重复地址检测:\t{uni.DuplicateAddressDetectionState}\n";
                    time = DateTime.UtcNow + TimeSpan.FromSeconds(uni.AddressValidLifetime);
                    time = time.ToLocalTime();
                    re  += $"\t\t有效期至:\t{time.ToString(lifeTimeFormat, System.Globalization.CultureInfo.CurrentCulture)}\n";
                    time = DateTime.UtcNow + TimeSpan.FromSeconds(uni.DhcpLeaseLifetime);
                    time = time.ToLocalTime();
                    re  += $"\t\tDHCP释放时间:\t{time.ToString(lifeTimeFormat, System.Globalization.CultureInfo.CurrentCulture)}\n";
                }
            }
            return(re);
        }
    // Tests all NICs for current DNS settings, and returns a list not matching
    // the input state
    static List <NetworkInterface> TestNICs(IP_CHOICES Choice)
    {
        List <NetworkInterface> ResetNICs = new List <NetworkInterface>();

        NetworkInterface[] NICs = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface NIC in NICs)
        {
            // Only full NICs we care about
            if (!IsReceiveOnly(NIC))
            {
                IPInterfaceProperties IPProps   = NIC.GetIPProperties();
                IPAddressCollection   ipCollDNS = IPProps.DnsAddresses;

                if (NIC.OperationalStatus != OperationalStatus.Up)
                {
                    continue;
                }

                foreach (IPAddress Addr in ipCollDNS)
                {
                    if (Addr.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6)
                    {
                        continue;
                    }

                    switch (Choice)
                    {
                    case IP_CHOICES.DEFAULT:

                        if (Addr.ToString() != "")
                        {
                            ResetNICs.Add(NIC);
                        }
                        break;

                    case IP_CHOICES.LOCALHOST:

                        if (Addr.ToString() != "127.0.0.1")
                        {
                            ResetNICs.Add(NIC);
                        }

                        break;

                    case IP_CHOICES.OPENDNS:

                        if ((Addr.ToString() != "208.67.220.220") && (Addr.ToString() != "208.67.222.222"))
                        {
                            ResetNICs.Add(NIC);
                        }

                        break;
                    }
                }
            }
        }

        return(ResetNICs);
    }
示例#31
0
        public void Test_ipv6_CountIPAddress2() {

            IPNetwork ipn = IPNetwork.Parse("::/0");
            var max = BigInteger.Pow(2, 128);
            using (IPAddressCollection ips = ipn.ListIPAddress()) {
                Assert.AreEqual(max, ips.Count, "Count");
            }
        }
        public void Test_ipv6_Reset()
        {
            IPNetwork ipn = IPNetwork.Parse("::/125");

            using (IPAddressCollection ips = IPNetwork.ListIPAddress(ipn)) {
                ips.Reset();
            }
        }
示例#33
0
 // Used	for	inserting the IPAddress	information	into the listbox.
 private void InsertAddresses(
     IPAddressCollection ipAddresses, string addressType)
 {
     foreach (IPAddress ipAddress in ipAddresses)
     {
         InsertAddress(ipAddress, addressType);
     }
 }
示例#34
0
 public LinuxGatewayIPAddressInformationCollection(IPAddressCollection col)
 {
     foreach (IPAddress item in col)
     {
         Add(new GatewayIPAddressInformationImpl(item));
     }
     is_readonly = true;
 }
示例#35
0
        static void Main(string[] args)
        {
            Parser.Default.ParseArguments <Options>(args)
            .WithParsed <Options>(o =>
            {
                string cidr      = o.Cidr;
                string outfile   = o.Outfile;
                int port         = o.Port;
                bool ssl         = o.SSL;
                string useragent = o.UserAgent;
                string proto;

                if (ssl == true)
                {
                    proto = "https";
                }
                else
                {
                    proto = "http";
                }

                IPNetwork ipn           = IPNetwork.Parse(cidr);
                IPAddressCollection ips = IPNetwork.ListIPAddress(ipn);

                Console.WriteLine("Scanning {0} IPs", ips.Count);

                Hashtable table = DefaultCreds.GetHashTable();

                string html = null;
                html       += HTML.GetHeader();

                Parallel.ForEach(ips, ip =>
                {
                    string url       = proto + "://" + ip + ":" + port;
                    string resp      = HTTP.MakeRequest(url, useragent);
                    string title     = HTTP.GetTitle(resp);
                    Image screenshot = Screenshot.Capture(url);

                    html += HTML.GetTitle(title);
                    html += HTML.GetAddress(url);

                    foreach (DictionaryEntry item in table)
                    {
                        if (title.ToLower().Contains(item.Key.ToString()))
                        {
                            string creds = HTML.GetDefaultCreds(table[item.Key].ToString());
                            html        += creds;
                        }
                    }

                    html += HTML.GetImg(Convert.ToBase64String(ImageConverter.ToByteArray(screenshot)));
                });

                html += HTML.GetFooter();

                File.Write(outfile, html);
            });
        }
 public LinuxIPInterfaceProperties(LinuxNetworkInterface lni)
     : base(lni)
 {
     _linuxNetworkInterface = lni;
     _gatewayAddresses = GetGatewayAddresses();
     _dhcpServerAddresses = GetDhcpServerAddresses();
     _winsServerAddresses = GetWinsServerAddresses();
     _ipv4Properties = new LinuxIPv4InterfaceProperties(lni);
     _ipv6Properties = new LinuxIPv6InterfaceProperties(lni);
 }
 internal IPAddressCollection ToIPAddressCollection()
 {
     IpAddrString str = this;
     IPAddressCollection addresss = new IPAddressCollection();
     if (str.IpAddress.Length != 0)
     {
         addresss.InternalAdd(IPAddress.Parse(str.IpAddress));
     }
     while (str.Next != IntPtr.Zero)
     {
         str = (IpAddrString) Marshal.PtrToStructure(str.Next, typeof(IpAddrString));
         if (str.IpAddress.Length != 0)
         {
             addresss.InternalAdd(IPAddress.Parse(str.IpAddress));
         }
     }
     return addresss;
 }
 private void GetPerAdapterInfo(uint index)
 {
     if (index != 0)
     {
         uint pOutBufLen = 0;
         SafeLocalFree pPerAdapterInfo = null;
         uint num2 = UnsafeNetInfoNativeMethods.GetPerAdapterInfo(index, SafeLocalFree.Zero, ref pOutBufLen);
         while (num2 == 0x6f)
         {
             try
             {
                 pPerAdapterInfo = SafeLocalFree.LocalAlloc((int) pOutBufLen);
                 num2 = UnsafeNetInfoNativeMethods.GetPerAdapterInfo(index, pPerAdapterInfo, ref pOutBufLen);
                 if (num2 == 0)
                 {
                     IpPerAdapterInfo info = (IpPerAdapterInfo) Marshal.PtrToStructure(pPerAdapterInfo.DangerousGetHandle(), typeof(IpPerAdapterInfo));
                     this.autoConfigEnabled = info.autoconfigEnabled;
                     this.autoConfigActive = info.autoconfigActive;
                     this.dnsAddresses = info.dnsServerList.ToIPAddressCollection();
                 }
                 continue;
             }
             finally
             {
                 if (this.dnsAddresses == null)
                 {
                     this.dnsAddresses = new IPAddressCollection();
                 }
                 if (pPerAdapterInfo != null)
                 {
                     pPerAdapterInfo.Close();
                 }
             }
         }
         if (this.dnsAddresses == null)
         {
             this.dnsAddresses = new IPAddressCollection();
         }
         if (num2 != 0)
         {
             throw new NetworkInformationException((int) num2);
         }
     }
 }
 internal static IPAddressCollection ToAddressCollection(IntPtr ptr, IPVersion versionSupported)
 {
     IPAddressCollection addresss = new IPAddressCollection();
     if (ptr != IntPtr.Zero)
     {
         IPEndPoint point;
         IpAdapterAddress address = (IpAdapterAddress) Marshal.PtrToStructure(ptr, typeof(IpAdapterAddress));
         AddressFamily family = (address.address.addressLength > 0x10) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
         SocketAddress socketAddress = new SocketAddress(family, address.address.addressLength);
         Marshal.Copy(address.address.address, socketAddress.m_Buffer, 0, address.address.addressLength);
         if (family == AddressFamily.InterNetwork)
         {
             point = (IPEndPoint) IPEndPoint.Any.Create(socketAddress);
         }
         else
         {
             point = (IPEndPoint) IPEndPoint.IPv6Any.Create(socketAddress);
         }
         addresss.InternalAdd(point.Address);
         while (address.next != IntPtr.Zero)
         {
             address = (IpAdapterAddress) Marshal.PtrToStructure(address.next, typeof(IpAdapterAddress));
             family = (address.address.addressLength > 0x10) ? AddressFamily.InterNetworkV6 : AddressFamily.InterNetwork;
             if (((family == AddressFamily.InterNetwork) && ((versionSupported & IPVersion.IPv4) > IPVersion.None)) || ((family == AddressFamily.InterNetworkV6) && ((versionSupported & IPVersion.IPv6) > IPVersion.None)))
             {
                 socketAddress = new SocketAddress(family, address.address.addressLength);
                 Marshal.Copy(address.address.address, socketAddress.m_Buffer, 0, address.address.addressLength);
                 if (family == AddressFamily.InterNetwork)
                 {
                     point = (IPEndPoint) IPEndPoint.Any.Create(socketAddress);
                 }
                 else
                 {
                     point = (IPEndPoint) IPEndPoint.IPv6Any.Create(socketAddress);
                 }
                 addresss.InternalAdd(point.Address);
             }
         }
     }
     return addresss;
 }
示例#40
0
		void ParseResolvConf ()
		{
			try {
				DateTime wt = File.GetLastWriteTime ("/etc/resolv.conf");
				if (wt <= last_parse)
					return;

				last_parse = wt;
				dns_suffix = "";
				dns_servers = new IPAddressCollection ();
				using (StreamReader reader = new StreamReader ("/etc/resolv.conf")) {
					string str;
					string line;
					while ((line = reader.ReadLine ()) != null) {
						line = line.Trim ();
						if (line.Length == 0 || line [0] == '#')
							continue;
						Match match = ns.Match (line);
						if (match.Success) {
							try {
								str = match.Groups ["address"].Value;
								str = str.Trim ();
								dns_servers.InternalAdd (IPAddress.Parse (str));
							} catch {
							}
						} else {
							match = search.Match (line);
							if (match.Success) {
								str = match.Groups ["domain"].Value;
								string [] parts = str.Split (',');
								dns_suffix = parts [0].Trim ();
							}
						}
					}
				}
			} catch {
			}
		}
 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;
         }
     }
 }
示例#42
0
 // Used	for	inserting the IPAddress	information	into the listbox.
 private void InsertAddresses(
     IPAddressCollection ipAddresses, string addressType)
 {
     foreach (IPAddress ipAddress in ipAddresses)
         InsertAddress(ipAddress, addressType);
 }
 internal bool Update(FixedInfo fixedInfo, IpAdapterInfo ipAdapterInfo)
 {
     try
     {
         foreach (IPExtendedAddress address in ipAdapterInfo.ipAddressList.ToIPExtendedAddressArrayList())
         {
             foreach (SystemUnicastIPAddressInformation information in this.unicastAddresses)
             {
                 if (address.address.Equals(information.Address))
                 {
                     information.ipv4Mask = address.mask;
                 }
             }
         }
         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) && (exception.ErrorCode != 13L)) && (((exception.ErrorCode != 0xe8L) && (exception.ErrorCode != 1L)) && (exception.ErrorCode != 2L)))
         {
             throw;
         }
         return false;
     }
     return true;
 }
示例#44
0
 public UnixIPInterfaceProperties(UnixNetworkInterface uni)
 {
     _uni = uni;
     _dnsSuffix = GetDnsSuffix();
     _dnsAddresses = GetDnsAddresses();
 }
        internal static IPAddressCollection MarshalIpAddressCollection(IntPtr ptr) {
            IPAddressCollection addressList = new IPAddressCollection();

            while (ptr != IntPtr.Zero) {
                IpAdapterAddress addressStructure =
                    (IpAdapterAddress)Marshal.PtrToStructure(ptr, typeof(IpAdapterAddress));
                IPAddress address = addressStructure.address.MarshalIPAddress();
                addressList.InternalAdd(address);
                ptr = addressStructure.next;
            }

            return addressList;
        }
示例#46
-1
 private static void ShowIPAddresses(string label, IPAddressCollection winsServers)
 {
     throw new NotImplementedException();
 }