-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
55 lines (40 loc) · 1.55 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#!/usr/bin/env python
# encoding: utf-8
from dnslib import DNSHeader, DNSRecord, RR, A
from gevent.server import DatagramServer
import re
class DnsCache():
def __init__(self):
self.cache = dict()
def get(self, domain):
return self.cache.get(domain, None)
def set(self, domain, info):
self.cache[domain] = info
def delete(self, domain):
self.cache.pop(domain, None)
cache = DnsCache()
class DnsQueryHandle():
def __init__(self, data):
self.data = data
self.parse_request()
def parse_request(self):
self.query = DNSRecord.parse(self.data)
self.qid = self.query.header.id
self.qtype = self.query.q.qtype
self.qname = self.query.q.qname
def handle_response(self):
self.handle_request()
self.reply = DNSRecord(DNSHeader(id=self.qid, qr=1, aa=1, ra=1), q=self.query.q, a=RR(self.qname, rdata=A(self.iplist[0])))
return self.reply.pack()
def handle_request(self):
next_query = DNSRecord.question(self.qname)
next_reply = next_query.send("114.114.114.114")
iplist = re.findall('\xC0.\x00\x01\x00\x01.{6}(.{4})', next_reply)
self.iplist = ['.'.join(str(ord(x)) for x in s) for s in iplist]
class DnsServer(DatagramServer):
def handle(self, data, address):
query = DnsQueryHandle(data)
self.socket.sendto(query.handle_response(), address)
if __name__ == "__main__":
print "DnsServer running"
DnsServer("127.0.0.1:53").serve_forever()