Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket resolve DNS with specific DNS server

I want to resolve DNS with specific DNS server, for example Google's 8.8.8.8. My actual Python code is:

import socket

def getIP(d):
    try:
        data = socket.gethostbyname(d)
        ip = repr(data)
        return True
    except Exception:
        # fail gracefully!
        return False

Is it possible using Python?

like image 911
seoexpert Avatar asked Jan 14 '16 15:01

seoexpert


1 Answers

You can use dnspython: http://www.dnspython.org/ On ubuntu/debian you can get it using:

sudo apt-get install python-dnspython

Otherwise get it via:

sudo pip install dnspython

Or download the source install it via:

sudo python setup.py install

Your code would be something like this:

from dns import resolver

res = resolver.Resolver()
res.nameservers = ['8.8.8.8']

answers = res.query('stackexchange.com')

for rdata in answers:
    print (rdata.address)

Edit: Since the OP seems to have issues using it on Mac OS X here is what I did to get it installed (for local user only):

git clone git://github.com/rthalley/dnspython.git
cd dnspython
python setup.py install --user
like image 195
gollum Avatar answered Oct 02 '22 20:10

gollum