/// <summary> /// Initiates the DNS Server's protocols and starts listening for requests. /// </summary> public void Start() { EndPoint EndPoint = new IPEndPoint(IPAddress.Any, 51); Server.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.PacketInformation, true); Server.Bind(EndPoint); Processor.LoadDomainNameTable(); //do database stuff. Server.BeginReceiveFrom(Data, 0, PACKET_LENGTH, SocketFlags.None, ref Sender, new AsyncCallback(Request), null); VerboseLog?.Invoke("Server has started listening for DNS requests."); }
/// <summary> /// Callback function for sending async DNS responses. /// </summary> /// <param name="result"></param> private void ResponseCompleted(IAsyncResult result) { try { EndPoint ep = (EndPoint)result.AsyncState; int bytesSend = Server.EndSendTo(result); if (bytesSend > 0) { VerboseLog?.Invoke($"Sent a response to {((IPEndPoint)ep).Address}:{((IPEndPoint)ep).Port}."); } } catch (Exception ex) { ErrorLog?.Invoke($"Error ending async response: '{ex.Message}'."); } }
/// <summary> /// Callback function for the Data recieve function. /// </summary> /// <param name="result"></param> private void Request(IAsyncResult result) { try { Server.EndReceiveFrom(result, ref Sender); bool success = DNSRequestHandler(Sender, Data); VerboseLog?.Invoke($"Received data from {((IPEndPoint)Sender).Address}:{((IPEndPoint)Sender).Port}. Response success: {success}."); Server.BeginReceiveFrom(Data, 0, PACKET_LENGTH, SocketFlags.None, ref Sender, new AsyncCallback(Request), null); } catch (SocketException sEx) { ErrorLog?.Invoke($"SocketException: '{sEx.Message}' for {((IPEndPoint)Sender).Address}."); } catch (DNSException dEx) { ErrorLog?.Invoke($"DNS Exception: '{dEx.Message}' for {((IPEndPoint)Sender).Address}."); } catch (Exception ex) { ErrorLog?.Invoke($"Unexpected Exception: '{ex.Message}'."); } }
private void Verbose(string text, params object[] args) { VerboseLog?.Invoke(string.Format(text + "\r\n", args)); }