Python解析DNS信息

Python解析DNS信息


import sys
import os
import struct
import socket
import re

host = 'www.baidu.com'
host = 'www.facebook.com'
host = 'centerqi.appspot.com'

index = os.urandom(2)
hoststr = ''.join(chr(len(x))+x for x in host.split('.'))
data = '%s\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00%s\x00\x00\x01\x00\x01' % (index, hoststr)
data = struct.pack('!H', len(data)) + data
address_family = socket.AF_INET
sock = None

dnsserver = '8.8.8.8'
sock = socket.socket(family=address_family)
sock.connect((dnsserver, 53))
sock.sendall(data)
rfile = sock.makefile('rb')
size = struct.unpack('!H', rfile.read(2))[0]
data = rfile.read(size)
ips = ['.'.join(str(ord(x)) for x in s) for s in re.findall('\xC0.\x00\x01\x00\x01.{6}(.{4})', data)]

print ips

另一种



#!/usr/bin/env python
# -*- coding: utf-8 -*-

import socket, SocketServer

def domain(data):
    data = data.split('\x01\x00\x00\x01\x00\x00\x00\x00\x00\x00')
    if data[0] != '\x00\x01':
        name = ''
        i = 0
        for x in data[1]:
            n = ord(x)
            if n == 0:
                break
            i = i + 1
            if n < 32:
                name = name + data[1][i:i + n] + '.'
        print len(name)

def answer(data):
    # for x in data:
        # print( ord(x) )
    data = data.split('\x00\x01\x00\x01')
    print data

class DNSUDPHandler(SocketServer.BaseRequestHandler):

    def handle(self):
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        socket.setdefaulttimeout(3)
        sock.sendto(self.request[0], ('223.5.5.5', 53))
        # domain(self.request[0])
        result = sock.recv(5120)
        answer(result)
        sock.close()
        self.request[1].sendto(result, self.client_address)

if __name__ == "__main__":
    server = SocketServer.UDPServer(("0.0.0.0", 53), DNSUDPHandler)
    server.serve_forever()