/// <summary> /// Function that processes the incoming data after an async callback returned. /// </summary> /// <param name="endpoint">The endpoint the data came from</param> /// <param name="Data">The dns packet data</param> /// <returns></returns> private bool DNSRequestHandler(EndPoint endpoint, byte[] Data) { //take out the headers, decide where to send it into the processor. if (Processor.IsDNSRequest(Data)) { DNSPacket packet = DNSPacket.RawToPacket(Data); if (packet.Type == DNSPacket.PacketType.Request) { string lookupData = Encoding.ASCII.GetString(packet.Data, 0, packet.Length); switch (packet.Lookup) { case DNSPacket.LookupType.Name: return(SendResponse(endpoint, packet.Lookup, Processor.LookupByName(lookupData.Split('.').Reverse().ToArray()))); case DNSPacket.LookupType.ARPA: return(SendResponse(endpoint, packet.Lookup, Processor.LookupByIp(lookupData))); } } else { throw new DNSException(packet, "Received a Response package while expecting only Request packages."); } } return(false); }
/// <summary> /// Connects with the provided DNS Server and retrieves the DNS name by looking up the given IP. /// </summary> /// <param name="ipadd">the ip address you want a DNS name for.</param> /// <returns></returns> public string RetrieveDNSName(string ipadd) { Connect(); DNSPacket packet = new DNSPacket { Type = DNSPacket.PacketType.Request, Lookup = DNSPacket.LookupType.ARPA, Data = Encoding.ASCII.GetBytes(ipadd) }; packet.Length = packet.Data.Length; byte[] raw = DNSPacket.PacketToRaw(packet); Client.Send(raw, packet.Length + 3); IPEndPoint ipep = new IPEndPoint(IPAddress.Parse(Address), 51); byte[] answer = Client.Receive(ref ipep); string responseData; if (answer.Length != 0 && ipep.Address.ToString().Equals(Address)) { //checks if the response came from the DNS server DNSPacket response = DNSPacket.RawToPacket(answer); if (response.Type == DNSPacket.PacketType.Response && response.Lookup == DNSPacket.LookupType.ARPA) { responseData = Encoding.ASCII.GetString(response.Data, 0, response.Length); } else { throw new DNSException(response, "Expected a Response and Name type, got something else."); } } else { throw new DNSException(null, "Received empty response or the response came from the wrong host."); } Disconnect(); return(responseData); }