deltap deltap - 4 months ago 20
Python Question

Check if field exists in DNS record using scapy

I am parsing DNS packets using scapy. Not all of the DNS Answer Records have all of the fields. For example, some Answers don't have rdata so

answer = packet.an[0].rdata


results in the error:

AttributeError: rdata


Is there a way of testing to see if the rdata field exists in an answer record? I know that you can check for layers

if packet.haslayer(DNS):
<code>


so you don't ask for layers that don't exist. Is there a parallel for fields within layers?

Answer

You could always do a try-except. Might not be as slick as what you're looking for, though.

try:
   answer = packet.an[0].rdata
except AttributeError:
   # do something