Created
September 29, 2012 10:50
-
-
Save hahastudio/3803682 to your computer and use it in GitHub Desktop.
dns_resolve
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import re | |
import socket | |
import struct | |
def dns_resolve(host, dnsserver): | |
assert isinstance(host, basestring) and isinstance(dnsserver, basestring) | |
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 = {True:socket.AF_INET6, False:socket.AF_INET}[':' in dnsserver] | |
sock = None | |
try: | |
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) | |
iplist = re.findall('\xC0.\x00\x01\x00\x01.{6}(.{4})', data) | |
return ['.'.join(str(ord(x)) for x in s) for s in iplist] | |
except Exception, e: | |
raise | |
finally: | |
if sock: | |
sock.close() | |
print dns_resolve('www.youtube.com', '8.8.8.8') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment