在Python中构建Dns数据包时遇到问题

时间:2014-07-17 21:42:38

标签: python dns packets

我正在尝试构建一个通过套接字发送的dns数据包。我不想使用任何库,因为我想直接访问发送它的套接字变量。每当我发送DNS数据包时,wireshark都会说它的格式不正确。我究竟做错了什么?

Dns数据包本身有些问题:     它说它有256个问题,没有类,没有类型

  class DnsPacketBuilder:

def __init__(self):
    pass

def build_packet(self, url):
    packet = struct.pack("H", 12049)  # Query Ids (Just 1 for now)
    packet += struct.pack("H", 256)  # Flags
    packet += struct.pack("H", 1)  # Questions
    packet += struct.pack("H", 0)  # Answers
    packet += struct.pack("H", 0)  # Authorities
    packet += struct.pack("H", 0)  # Additional
    split_url = url.split(".")
    for part in split_url:
        packet += struct.pack("B", len(part))
        for byte in bytes(part):
            packet += struct.pack("c", byte)
    packet += struct.pack("B", 0)  # End of String
    packet += struct.pack("H", 1)  # Query Type
    packet += struct.pack("H", 1)  # Query Class
    return packet

# Sending the packet
builder = DnsPacketBuilder()
packet = builder.build_packet("www.northeastern.edu")
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('', 8888))
sock.settimeout(2)
sock.sendto(bytes(packet), ("208.67.222.222", 53))
print("Packet Sent")
data, addr = sock.recvfrom(1024)
print("Response: " + data)
sock.close()

1 个答案:

答案 0 :(得分:4)

您的系统本身正在使用“小端”字节顺序。

您需要使用">H"中的struct.pack() format string将16位字段的字节顺序反转为“big endian”(又称“网络顺序”)。