Skip to content

Instantly share code, notes, and snippets.

@johnbumgarner
Last active June 10, 2024 17:37
Show Gist options
  • Save johnbumgarner/166b6371f975c8e0a0aeae2516771039 to your computer and use it in GitHub Desktop.
Save johnbumgarner/166b6371f975c8e0a0aeae2516771039 to your computer and use it in GitHub Desktop.
This function is designed to extract DNS elements from a PCAP packet.
import pyshark
from typing import Union
def extract_dns_information(packet) -> Union[str, None]:
"""
Extract DNS elements from a PCAP packet.
:param packet: PCAP packet
:return: A string with DNS information or None if no DNS information is found in the packet
:rtype: str or NoneType
"""
if hasattr(packet, 'udp') and packet[packet.transport_layer].dstport == '53':
try:
source_address = packet.ip.src
if hasattr(packet.dns, 'qry_name'):
dns_location = packet.dns.qry_name
return f'DNS Request from IP: {source_address} to DNS Name: {dns_location}'
elif hasattr(packet.dns, 'resp_name'):
dns_location = packet.dns.resp_name
return f'DNS Response from IP: {source_address} to DNS Name: {dns_location}'
except AttributeError:
pass
return None
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment