Esempio n. 1
0
        public static NameServerAddress[] GetNameServersFromResponse(DnsDatagram response, bool preferIPv6)
        {
            List <NameServerAddress> nameServers = new List <NameServerAddress>(response.Authority.Length);

            DnsResourceRecord[] authorityRecords;

            if ((response.Question.Length > 0) && (response.Question[0].Type == DnsResourceRecordType.NS) && (response.Answer.Length > 0))
            {
                authorityRecords = response.Answer;
            }
            else
            {
                authorityRecords = response.Authority;
            }

            foreach (DnsResourceRecord authorityRecord in authorityRecords)
            {
                if (authorityRecord.Type == DnsResourceRecordType.NS)
                {
                    DnsNSRecord nsRecord = (DnsNSRecord)authorityRecord.RDATA;
                    IPEndPoint  endPoint = null;

                    //find ip address of authoritative name server from additional records
                    foreach (DnsResourceRecord rr in response.Additional)
                    {
                        if (nsRecord.NSDomainName.Equals(rr.Name, StringComparison.OrdinalIgnoreCase))
                        {
                            switch (rr.Type)
                            {
                            case DnsResourceRecordType.A:
                                endPoint = new IPEndPoint(((DnsARecord)rr.RDATA).Address, 53);
                                nameServers.Add(new NameServerAddress(nsRecord.NSDomainName, endPoint));
                                break;

                            case DnsResourceRecordType.AAAA:
                                endPoint = new IPEndPoint(((DnsAAAARecord)rr.RDATA).Address, 53);

                                if (preferIPv6)
                                {
                                    nameServers.Add(new NameServerAddress(nsRecord.NSDomainName, endPoint));
                                }

                                break;
                            }
                        }
                    }

                    if (endPoint == null)
                    {
                        nameServers.Add(new NameServerAddress(new DomainEndPoint(nsRecord.NSDomainName, 53)));
                    }
                }
            }

            NameServerAddress[] nsArray = nameServers.ToArray();

            DnsClient.ShuffleArray(nsArray);

            if (preferIPv6)
            {
                Array.Sort(nsArray);
            }

            return(nsArray);
        }