java.lang.Object
org.minidns.dnsmessage.DnsMessage

public class DnsMessageextends Object
A DNS message as defined by RFC 1035. The message consists of a header and 4 sections: question, answer, nameserver and addition resource record section. A message can either be parsed (DnsMessage(byte[])) or serialized (toArray()).
See Also:
  • Field Details

    • LOGGER

      private static final Logger LOGGER
      Logger for the DNS message code.
    • id

      public final int id
      The DNS message id.
    • opcode

      public final DnsMessage.OPCODE opcode
      The DNS message opcode.
    • responseCode

      public final DnsMessage.RESPONSE_CODE responseCode
      The response code of this dns message.
    • qr

      public final boolean qr
      The QR flag of the DNS message header. Note that this will be true if the message is a response and false if it is a query.
      See Also:
    • authoritativeAnswer

      public final boolean authoritativeAnswer
      True if this is a authorative response. If set, the responding nameserver is an authority for the domain name in the question section. Note that the answer section may have multiple owner names because of aliases. This flag corresponds to the name which matches the query name, or the first owner name in the query section.
      See Also:
    • truncated

      public final boolean truncated
      True if message is truncated. Then TCP should be used.
    • recursionDesired

      public final boolean recursionDesired
      True if the server should recurse.
    • recursionAvailable

      public final boolean recursionAvailable
      True if recursion is possible.
    • authenticData

      public final boolean authenticData
      True if the server regarded the response as authentic.
    • checkingDisabled

      public final boolean checkingDisabled
      True if the server should not perform DNSSEC validation before returning the result.
    • questions

      public final List<Question> questions
      The question section content. Usually there will be only one question.

      This list is unmodifiable.

    • answerSection

      public final List<Record<? extends Data>> answerSection
      The answers section records. Note that it is not guaranteed that all records found in this section will be direct answers to the question in the query. If DNSSEC is used, then this section also contains the RRSIG record.

      This list is unmodifiable.

    • authoritySection

      public final List<Record<? extends Data>> authoritySection
      The Authority Section. Note that it is not guaranteed that this section only contains nameserver records. If DNSSEC is used, then this section could also contain a NSEC(3) record.

      This list is unmodifiable.

    • additionalSection

      public final List<Record<? extends Data>> additionalSection
      The additional section. It eventually contains RRs which relate to the query.

      This list is unmodifiable.

    • optRrPosition

      public final int optRrPosition
      The position of the OPT pseudo-record in the additional section, or -1 if none.
    • edns

      private Edns edns
      The optional but very common EDNS information. Note that this field is lazily populated.
    • receiveTimestamp

      public final long receiveTimestamp
      The receive timestamp. Set only if this message was created via parse. This should be used to evaluate TTLs.
    • byteCache

      private byte[] byteCache
      Cached serialized byte array, used to avoid re-serializing on repeated calls.
    • toStringCache

      private String toStringCache
      Cached string representation of this message, built on first call to toString().
    • terminalOutputCache

      private String terminalOutputCache
      Cached terminal-formatted output string, built on first call to asTerminalOutput().
    • answersMinTtlCache

      private long answersMinTtlCache
      Cached minimum TTL value across all answer records, or -1 if not yet computed.
    • normalizedVersionCache

      private DnsMessage normalizedVersionCache
      Cached normalized version of this message (id set to 0), built on first call to asNormalizedVersion().
    • hashCodeCache

      private transient Integer hashCodeCache
      Cached hash code, computed from the serialized byte representation on first call to hashCode().
  • Constructor Details

    • DnsMessage

      protected DnsMessage(DnsMessage.Builder builder)
      Construct a DNS message from the state of the given builder.
      Parameters:
      builder - the builder holding the header flags and the sections.
    • DnsMessage

      public DnsMessage(byte[] data) throws IOException
      Build a DNS Message based on a binary DNS message.
      Parameters:
      data - The DNS message data.
      Throws:
      IOException - On read errors.
    • DnsMessage

      private DnsMessage(DnsMessage message)
      Constructs an normalized version of the given DnsMessage by setting the id to '0'.
      Parameters:
      message - the message of which normalized version should be constructed.
  • Method Details

    • getOptRrPosition

      private static int getOptRrPosition(List<Record<? extends Data>> additionalSection)
      Position of the OPT record in the additional section.
      Parameters:
      additionalSection - the additional records
      Returns:
      the position, negative if absent
    • toArray

      public byte[] toArray()
      Generate a binary dns packet out of this message.
      Returns:
      byte[] the binary representation.
    • asDatagram

      public DatagramPacket asDatagram(InetAddress address, int port)
      Wrap the serialized message in a UDP datagram.
      Parameters:
      address - the address of the peer the message is addressed to.
      port - the UDP port of that peer, normally 53.
      Returns:
      a datagram carrying the serialized message.
    • writeTo

      public void writeTo(OutputStream outputStream) throws IOException
      Write the serialized message to the given stream, prefixed with its length as required by the DNS over TCP framing of RFC 1035 § 4.2.2.
      Parameters:
      outputStream - the stream to write to.
      Throws:
      IOException - On write errors.
    • writeTo

      public void writeTo(OutputStream outputStream, boolean writeLength) throws IOException
      Write the serialized message to the given stream.
      Parameters:
      outputStream - the stream to write to.
      writeLength - true to prefix the message with its 16 bit length, false to write the bare message.
      Throws:
      IOException - On write errors.
    • getInByteBuffer

      public ByteBuffer getInByteBuffer()
      Wrap the serialized message in a byte buffer.
      Returns:
      a buffer over a private copy of the serialized message.
    • serialize

      private byte[] serialize()
      Writes the message out as bytes.
      Returns:
      the message bytes
    • calculateHeaderBitmap

      int calculateHeaderBitmap()
      Compute the DNS header bitmap
      Returns:
      the 16 bit header field with the QR, opcode, AA, TC, RD, RA, AD and CD bits and the response code packed into it.
    • getQuestion

      public Question getQuestion()
      Retrieve the first question of the question section.
      Returns:
      the first question.
    • copyQuestions

      public List<Question> copyQuestions()
      Copy the questions found in the question section.
      Returns:
      a copy of the question section questions.
      See Also:
    • copyAnswers

      public List<Record<? extends Data>> copyAnswers()
      Copy the records found in the answer section into a new list.
      Returns:
      a copy of the answer section records.
      See Also:
    • copyAuthority

      public List<Record<? extends Data>> copyAuthority()
      Copy the records found in the authority section into a new list.
      Returns:
      a copy of the authority section records.
      See Also:
    • getEdns

      public Edns getEdns()
      Retrieve the EDNS information of this message.
      Returns:
      the EDNS information built from the OPT pseudo record, or null if this message has none.
    • getOptPseudoRecord

      public Record<OPT> getOptPseudoRecord()
      Retrieve the OPT pseudo record of this message.
      Returns:
      the OPT record of the additional section, or null if this message has none.
    • isDnssecOk

      public boolean isDnssecOk()
      Check if the EDNS DO (DNSSEC OK) flag is set.
      Returns:
      true if the DO flag is set.
    • toString

      public String toString()
      Renders the whole message, caching the result for later calls.
      Overrides:
      toString in class Object
    • asTerminalOutput

      public String asTerminalOutput()
      Format the DnsMessage object in a way suitable for terminal output. The format is loosely based on the output provided by dig.
      Returns:
      This message as a String suitable for terminal output.
    • getAnswersFor

      public <D extends Data> Set<D> getAnswersFor(Question q)
      Collect the payloads of the answer records matching the given question.
      Type Parameters:
      D - the payload type the collected payloads are cast to.
      Parameters:
      q - the question whose name, type and class the records must match.
      Returns:
      the distinct payloads of the matching answer records, or null if this message has a response code other than NO_ERROR.
    • getAnswersMinTtl

      public long getAnswersMinTtl()
      Get the minimum TTL from all answers in seconds.
      Returns:
      the minimum TTL from all answers in seconds.
    • asBuilder

      public DnsMessage.Builder asBuilder()
      Create a builder holding a copy of the content of this message.
      Returns:
      a builder initialized from this message.
    • asNormalizedVersion

      public DnsMessage asNormalizedVersion()
      Retrieve the copy of this message with the message id set to 0.
      Returns:
      a message with the content of this one but with the id zeroed, so that messages differing only in the id compare as equal.
    • getResponseBuilder

      public DnsMessage.Builder getResponseBuilder(DnsMessage.RESPONSE_CODE responseCode)
      Create a builder for a response to this query.
      Parameters:
      responseCode - the status of the response to put into the header.
      Returns:
      a builder with the QR flag set and with the id and the first question of this message; only usable while this message is a query.
    • hashCode

      public int hashCode()
      Hashes the serialized byte representation, caching the computed value.
      Overrides:
      hashCode in class Object
    • filterSectionByType

      private <D extends Data> List<Record<D>> filterSectionByType(boolean stopOnFirst, DnsMessage.SectionName sectionName, Class<D> type)
      Filters a section's records by data type.
      Type Parameters:
      D - the data type of the records
      Parameters:
      stopOnFirst - true to stop after the first match
      sectionName - the section to filter
      type - the data class to keep
      Returns:
      the matching records
    • filterSectionByType

      private <D extends Data> List<Record<D>> filterSectionByType(DnsMessage.SectionName sectionName, Class<D> type)
      Filters a section's records by data type.
      Type Parameters:
      D - the data type of the records
      Parameters:
      sectionName - the section to filter
      type - the data class to keep
      Returns:
      the matching records
    • getFirstOfType

      private <D extends Data> Record<D> getFirstOfType(DnsMessage.SectionName sectionName, Class<D> type)
      The first record of the given type.
      Type Parameters:
      D - the data type of the record
      Parameters:
      sectionName - the section to search
      type - the data class
      Returns:
      the record, null if absent
    • filterAnswerSectionBy

      public <D extends Data> List<Record<D>> filterAnswerSectionBy(Class<D> type)
      Collect the answer records holding the given payload type.
      Type Parameters:
      D - the payload type the collected records are typed as.
      Parameters:
      type - the payload type to match.
      Returns:
      the matching records of the answer section, in message order.
    • filterAuthoritySectionBy

      public <D extends Data> List<Record<D>> filterAuthoritySectionBy(Class<D> type)
      Collect the authority section records holding the given payload type.
      Type Parameters:
      D - the payload type the collected records are typed as.
      Parameters:
      type - the payload type to match.
      Returns:
      the matching records of the authority section, in message order.
    • filterAdditionalSectionBy

      public <D extends Data> List<Record<D>> filterAdditionalSectionBy(Class<D> type)
      Collect the additional section records holding the given payload type.
      Type Parameters:
      D - the payload type the collected records are typed as.
      Parameters:
      type - the payload type to match.
      Returns:
      the matching records of the additional section, in message order.
    • getFirstOfTypeFromAnswerSection

      public <D extends Data> Record<D> getFirstOfTypeFromAnswerSection(Class<D> type)
      Retrieve the first answer record holding the given payload type.
      Type Parameters:
      D - the payload type the returned record is typed as.
      Parameters:
      type - the payload type to match.
      Returns:
      the first matching record of the answer section, or null if there is none.
    • getFirstOfTypeFromAuthoritySection

      public <D extends Data> Record<D> getFirstOfTypeFromAuthoritySection(Class<D> type)
      Retrieve the first authority section record holding the given payload type.
      Type Parameters:
      D - the payload type the returned record is typed as.
      Parameters:
      type - the payload type to match.
      Returns:
      the first matching record of the authority section, or null if there is none.
    • getFirstOfTypeFromAdditionalSection

      public <D extends Data> Record<D> getFirstOfTypeFromAdditionalSection(Class<D> type)
      Retrieve the first additional section record holding the given payload type.
      Type Parameters:
      D - the payload type the returned record is typed as.
      Parameters:
      type - the payload type to match.
      Returns:
      the first matching record of the additional section, or null if there is none.
    • equals

      public boolean equals(Object other)
      Compares the serialized wire form against another message.
      Overrides:
      equals in class Object
    • builder

      public static DnsMessage.Builder builder()
      Create an empty builder for a new DNS message.
      Returns:
      a builder with the default header flags and empty sections.