/// <summary> /// Function that sends the async responses to the client. /// </summary> /// <param name="endpoint">The endpoint to send the response to</param> /// <param name="type">Packet type</param> /// <param name="record">The DNSRecord to send back</param> /// <returns></returns> private bool SendResponse(EndPoint endpoint, DNSPacket.LookupType type, DNSRecord record) { if (record == null) { return(false); } DNSPacket packet = new DNSPacket { Type = DNSPacket.PacketType.Response, Lookup = type, Data = (type == DNSPacket.LookupType.Name) ? Encoding.ASCII.GetBytes(record.Address) : Encoding.ASCII.GetBytes(string.Join(",", record.SubDomains.Select(n => n.Domain)).ToCharArray(), 0, 254) }; packet.Length = packet.Data.Length; byte[] sendBuffer = DNSPacket.PacketToRaw(packet); try { Server.BeginSendTo(sendBuffer, 0, sendBuffer.Length, SocketFlags.None, endpoint, new AsyncCallback(ResponseCompleted), endpoint); return(true); } catch (Exception ex) { ErrorLog?.Invoke($"Error sending async response: '{ex.Message}'."); 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); }