Skip to content

Instantly share code, notes, and snippets.

@bk-ty
Created May 27, 2025 12:40
Show Gist options
  • Save bk-ty/f1196a53112238e7a88c4419b8afac22 to your computer and use it in GitHub Desktop.
Save bk-ty/f1196a53112238e7a88c4419b8afac22 to your computer and use it in GitHub Desktop.
#!/bin/bash
# Usage: ./dns-lookup.sh example.com
HOST="$1"
DNS_SERVER=${2:-8.8.8.8}
PORT=53
if [[ -z "$HOST" ]]; then
echo "Usage: $0 <hostname> [dns_server]"
exit 1
fi
# Build query header
TXID=$(printf "%02x%02x" $((RANDOM%256)) $((RANDOM%256)))
HEADER="${TXID}01000001000000000000"
# Build query question section
QNAME=""
IFS='.' read -ra PARTS <<< "$HOST"
for PART in "${PARTS[@]}"; do
LEN=$(printf "%02x" ${#PART})
HEX=$(echo -n "$PART" | xxd -p)
QNAME="${QNAME}${LEN}${HEX}"
done
QNAME="${QNAME}00" # end of QNAME
QTYPE="0001" # A record
QCLASS="0001" # IN
QUERY="${HEADER}${QNAME}${QTYPE}${QCLASS}"
# Convert hex to binary and send over UDP
exec 3<>/dev/udp/${DNS_SERVER}/${PORT}
echo -n -e "$(echo "$QUERY" | sed 's/../\\x&/g')" >&3
RESPONSE=$(dd bs=1 count=512 <&3 2>/dev/null | xxd -p -c 512)
# Extract and print A record IP addresses
echo "$RESPONSE" | grep -oP '(?<=c00c00010001.{8})[0-9a-f]{8}' | while read -r iphex; do
printf "%d.%d.%d.%d\n" "0x${iphex:0:2}" "0x${iphex:2:2}" "0x${iphex:4:2}" "0x${iphex:6:2}"
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment