예제 #1
0
        public void LookupAsync(string hostnameOrIPAddress, DNSLookupOptions DNSLookupOptions)
        {
            Task.Run(() =>
            {
                // This will convert the query to an Arpa request
                if (DNSLookupOptions.Type == QType.PTR)
                {
                    if (IPAddress.TryParse(hostnameOrIPAddress, out IPAddress ip))
                    {
                        hostnameOrIPAddress = Resolver.GetArpaFromIp(ip);
                    }
                }

                if (DNSLookupOptions.Type == QType.NAPTR)
                {
                    hostnameOrIPAddress = Resolver.GetArpaFromEnum(hostnameOrIPAddress);
                }

                if (DNSLookupOptions.UseCustomDNSServer)
                {
                    DNSResolver.DnsServer = DNSLookupOptions.CustomDNSServer;
                }

                DNSResolver.Recursion     = DNSLookupOptions.Recursion;
                DNSResolver.TransportType = DNSLookupOptions.TransportType;
                DNSResolver.Retries       = DNSLookupOptions.Attempts;
                DNSResolver.TimeOut       = DNSLookupOptions.Timeout;

                Response dnsResponse = DNSResolver.Query(hostnameOrIPAddress, DNSLookupOptions.Type, DNSLookupOptions.Class);

                // If there was an error... return
                if (!string.IsNullOrEmpty(dnsResponse.Error))
                {
                    OnLookupError(new DNSLookupErrorArgs(dnsResponse.Error, DNSResolver.DnsServer));
                    return;
                }

                // Process the results...
                ProcessResponse(dnsResponse);

                // If we get a CNAME back (from a result), do a second request and try to get the A, AAAA etc...
                if (DNSLookupOptions.ResolveCNAME && DNSLookupOptions.Type != QType.CNAME)
                {
                    foreach (RecordCNAME r in dnsResponse.RecordsCNAME)
                    {
                        Response DNSResponse2 = DNSResolver.Query(r.CNAME, DNSLookupOptions.Type, DNSLookupOptions.Class);

                        if (!string.IsNullOrEmpty(DNSResponse2.Error))
                        {
                            OnLookupError(new DNSLookupErrorArgs(DNSResponse2.Error, DNSResolver.DnsServer));
                            continue;
                        }

                        ProcessResponse(DNSResponse2);
                    }
                }

                OnLookupComplete(new DNSLookupCompleteArgs(dnsResponse.Server.ToString(), dnsResponse.Questions.Count, dnsResponse.Answers.Count, dnsResponse.Authorities.Count, dnsResponse.Additionals.Count, dnsResponse.MessageSize));
            });
        }
예제 #2
0
        public static Tuple <IPAddress, List <string> > ResolvePTR(IPAddress host, DNSLookupOptions options)
        {
            // DNS server list
            List <string> dnsServers = new List <string>();

            if (options.UseCustomDNSServer)
            {
                options.CustomDNSServers.ForEach(x => dnsServers.Add(x));
            }
            else // Use windows default dns server, but filter/remove IPv6 site local addresses (fec0:0:0:0:ffff::)
            {
                dnsResolver.DnsServers.Where(x => !x.Address.ToString().StartsWith(@"fec0")).Select(y => y.Address.ToString()).ToList().ForEach(x => dnsServers.Add(x));
            }

            // PTR
            string name = Resolver.GetArpaFromIp(host);

            int port = options.UseCustomDNSServer ? options.Port : Resolver.DefaultPort;

            string        dnsServerIPAddress = string.Empty;
            List <string> ptrResults         = new List <string>();

            foreach (string dnsServer in dnsServers)
            {
                dnsServerIPAddress = dnsServer;

                // Create a new for each request
                Resolver resolver = new Resolver(dnsServer, port)
                {
                    Recursion     = options.Recursion,
                    TransportType = options.TransportType,
                    UseCache      = options.UseResolverCache,
                    Retries       = options.Attempts,
                    TimeOut       = options.Timeout
                };

                Response dnsResponse = resolver.Query(name, QType.PTR);

                if (!string.IsNullOrEmpty(dnsResponse.Error)) // On error... try next dns server...
                {
                    continue;
                }

                // PTR
                foreach (RecordPTR r in dnsResponse.RecordsPTR)
                {
                    ptrResults.Add(r.PTRDNAME);
                }

                // If we got results, break... else --> check next dns server
                if (ptrResults.Count > 0)
                {
                    break;
                }
            }

            return(new Tuple <IPAddress, List <string> >(IPAddress.Parse(dnsServerIPAddress), ptrResults));
        }
예제 #3
0
 public static Task <Tuple <IPAddress, List <string> > > ResolvePTRAsync(IPAddress host, DNSLookupOptions options)
 {
     return(Task.Run(() => ResolvePTR(host, options)));
 }
예제 #4
0
        public void ResolveAsync(List <string> hosts, DNSLookupOptions options)
        {
            Task.Run(() =>
            {
                // DNS server list
                var dnsServers = new List <string>();

                if (options.UseCustomDNSServer)
                {
                    options.CustomDNSServers.ForEach(x => dnsServers.Add(x));
                }
                else // Use windows default dns server, but filter/remove IPv6 site local addresses (fec0:0:0:0:ffff::)
                {
                    DNSResolver.DnsServers.Where(x => !x.Address.ToString().StartsWith(@"fec0")).Select(y => y.Address.ToString()).ToList().ForEach(x => dnsServers.Add(x));
                }

                // Foreach host
                foreach (var host in hosts)
                {
                    // Default
                    var name = host;

                    var dnsSuffix = string.Empty;

                    if (name.IndexOf(".", StringComparison.OrdinalIgnoreCase) == -1)
                    {
                        if (options.AddDNSSuffix)
                        {
                            dnsSuffix = options.UseCustomDNSSuffix ? options.CustomDNSSuffix : IPGlobalProperties.GetIPGlobalProperties().DomainName;
                        }
                    }

                    // Append dns suffix to hostname
                    if (!string.IsNullOrEmpty(dnsSuffix))
                    {
                        name += $".{dnsSuffix}";
                    }

                    switch (options.Type)
                    {
                    // PTR
                    case QType.PTR:
                        if (IPAddress.TryParse(name, out IPAddress ip))
                        {
                            name = Resolver.GetArpaFromIp(ip);
                        }
                        break;

                    // NAPTR
                    case QType.NAPTR:
                        name = Resolver.GetArpaFromEnum(name);
                        break;
                    }

                    var port = options.UseCustomDNSServer ? options.Port : Resolver.DefaultPort;

                    Parallel.ForEach(dnsServers, dnsServer =>
                    {
                        // Create a new for each request
                        var resolver = new Resolver(dnsServer, port)
                        {
                            Recursion     = options.Recursion,
                            TransportType = options.TransportType,
                            UseCache      = options.UseResolverCache,
                            Retries       = options.Attempts,
                            TimeOut       = options.Timeout
                        };

                        var dnsResponse = resolver.Query(name, options.Type, options.Class);

                        // If there was an error... return
                        if (!string.IsNullOrEmpty(dnsResponse.Error))
                        {
                            OnLookupError(new DNSLookupErrorArgs(dnsResponse.Error, resolver.DnsServer));
                            return;
                        }

                        // Process the results...
                        ProcessResponse(dnsResponse);

                        // If we get a CNAME back (from an ANY result), do a second request and try to get the A, AAAA etc...
                        if (!options.ResolveCNAME || options.Type != QType.ANY)
                        {
                            return;
                        }

                        foreach (var record in dnsResponse.RecordsCNAME)
                        {
                            var dnsResponse2 = resolver.Query(record.CNAME, options.Type, options.Class);

                            if (!string.IsNullOrEmpty(dnsResponse2.Error))
                            {
                                OnLookupError(new DNSLookupErrorArgs(dnsResponse2.Error, resolver.DnsServer));
                                continue;
                            }

                            ProcessResponse(dnsResponse2);
                        }
                    });
                }

                OnLookupComplete();
            });
        }
예제 #5
0
        public void ScanAsync(IPAddress[] ipAddresses, IPScannerOptions ipScannerOptions, CancellationToken cancellationToken)
        {
            // Start the scan in a separat task
            Task.Run(() =>
            {
                progressValue = 0;

                // Modify the ThreadPool for better performance
                ThreadPool.GetMinThreads(out int workerThreads, out int completionPortThreads);
                ThreadPool.SetMinThreads(workerThreads + ipScannerOptions.Threads, completionPortThreads + ipScannerOptions.Threads);

                try
                {
                    ParallelOptions parallelOptions = new ParallelOptions()
                    {
                        CancellationToken      = cancellationToken,
                        MaxDegreeOfParallelism = ipScannerOptions.Threads
                    };

                    string localHostname = ipScannerOptions.ResolveHostname ? Dns.GetHostName() : string.Empty;

                    Parallel.ForEach(ipAddresses, parallelOptions, ipAddress =>
                    {
                        PingInfo pingInfo = new PingInfo();
                        bool pingable     = false;

                        // PING
                        using (System.Net.NetworkInformation.Ping ping = new System.Net.NetworkInformation.Ping())
                        {
                            for (int i = 0; i < ipScannerOptions.ICMPAttempts; i++)
                            {
                                try
                                {
                                    PingReply pingReply = ping.Send(ipAddress, ipScannerOptions.ICMPTimeout, ipScannerOptions.ICMPBuffer);

                                    if (IPStatus.Success == pingReply.Status)
                                    {
                                        pingInfo = new PingInfo(pingReply.Address, pingReply.Buffer.Count(), pingReply.RoundtripTime, pingReply.Options.Ttl, pingReply.Status);

                                        pingable = true;
                                        break; // Continue with the next checks...
                                    }
                                    else
                                    {
                                        pingInfo = new PingInfo(ipAddress, pingReply.Status);
                                    }
                                }
                                catch (PingException)
                                {
                                }

                                // Don't scan again, if the user has canceled (when more than 1 attempt)
                                if (cancellationToken.IsCancellationRequested)
                                {
                                    break;
                                }
                            }
                        }

                        if (pingable || ipScannerOptions.ShowScanResultForAllIPAddresses)
                        {
                            // DNS
                            string hostname = string.Empty;

                            if (ipScannerOptions.ResolveHostname)
                            {
                                DNSLookupOptions options = new DNSLookupOptions()
                                {
                                    UseCustomDNSServer = ipScannerOptions.UseCustomDNSServer,
                                    CustomDNSServers   = ipScannerOptions.CustomDNSServer,
                                    Port             = ipScannerOptions.DNSPort,
                                    Attempts         = ipScannerOptions.DNSAttempts,
                                    Timeout          = ipScannerOptions.DNSTimeout,
                                    TransportType    = ipScannerOptions.DNSTransportType,
                                    UseResolverCache = ipScannerOptions.DNSUseResolverCache,
                                    Recursion        = ipScannerOptions.DNSRecursion,
                                };

                                hostname = DNSLookup.ResolvePTR(ipAddress, options).Item2.FirstOrDefault();
                            }

                            // ARP
                            PhysicalAddress macAddress = null;
                            string vendor = string.Empty;

                            if (ipScannerOptions.ResolveMACAddress)
                            {
                                // Get info from arp table
                                ARPTableInfo arpTableInfo = ARPTable.GetTable().Where(p => p.IPAddress.ToString() == ipAddress.ToString()).FirstOrDefault();

                                if (arpTableInfo != null)
                                {
                                    macAddress = arpTableInfo.MACAddress;
                                }

                                // Check if it is the local mac
                                if (macAddress == null)
                                {
                                    NetworkInterfaceInfo networkInferfaceInfo = NetworkInterface.GetNetworkInterfaces().Where(p => p.IPv4Address.Contains(ipAddress)).FirstOrDefault();

                                    if (networkInferfaceInfo != null)
                                    {
                                        macAddress = networkInferfaceInfo.PhysicalAddress;
                                    }
                                }

                                // Vendor lookup
                                if (macAddress != null)
                                {
                                    OUIInfo info = OUILookup.Lookup(macAddress.ToString()).FirstOrDefault();

                                    if (info != null)
                                    {
                                        vendor = info.Vendor;
                                    }
                                }
                            }

                            OnHostFound(new IPScannerHostFoundArgs(pingInfo, hostname, macAddress, vendor));
                        }

                        IncreaseProcess();
                    });

                    OnScanComplete();
                }
                catch (OperationCanceledException)  // If user has canceled
                {
                    // Check if the scan is already complete...
                    if (ipAddresses.Length == progressValue)
                    {
                        OnScanComplete();
                    }
                    else
                    {
                        OnUserHasCanceled();
                    }
                }
                finally
                {
                    // Reset the ThreadPool to default
                    ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads);
                    ThreadPool.SetMinThreads(workerThreads - ipScannerOptions.Threads, completionPortThreads - ipScannerOptions.Threads);
                }
            });
        }