User avatar
RaspberryPiBeginners
Posts: 218
Joined: Fri May 11, 2012 6:54 am
Location: Soham, Cambridgeshire
Contact: Website

Problems with handling "socket.gaierror"

Sun Feb 10, 2013 3:50 pm

I'm trying to run some python code that looks to see if DNS resolution is working. When it works this is great. But when it cant resolve it stoops the script from running and bombs out with this error.
Traceback (most recent call last):
File "testingfile.py", line 10, in <module>
externaldns = socket.gethostbyname('www.google.co.uk') # result from hosts file
socket.gaierror: [Errno -5] No address associated with hostname
The Error isn't the problem it's the fact that the code/scripts stops running.
Ideally i don't want it to print the error to screen and not to stop the script from running.

This code is what im working with

Code: Select all

#!/usr/bin/python

# Import required libraries
import urllib2
import os
import socket
#-------------
#Check For DNS
#-------------
externaldns = socket.gethostbyname('www.google.co.uk') # result from hosts file
print "---------------"
print "External DNS"
print "---------------"
print externaldns + " << Local DNS"
if "socket.gaierror" in externaldns:
    print "External DNS resolution failed"
Click here for my unofficial YouTube Channel > http://goo.gl/oFYBD

cae2100
Posts: 143
Joined: Tue Jan 08, 2013 10:35 am
Contact: Website

Re: Problems with handling "socket.gaierror"

Mon Feb 11, 2013 5:40 am

you could try something like this, and it'd just skip over the socket part when it cannot connect.

Code: Select all

#!/usr/bin/python

    # Import required libraries
import urllib2
import os
import socket
    #-------------
    #Check For DNS
    #-------------
try:
    externaldns = socket.gethostbyname('www.google.co.uk') # result from hosts file
    print "---------------"
    print "External DNS"
    print "---------------"
    print externaldns + " << Local DNS"
except:
    print "External DNS resolution failed"
If it isnt smoking and blown into pieces, it's not pushed far enough yet. :P
http://cae2100.wordpress.com

User avatar
RaspberryPiBeginners
Posts: 218
Joined: Fri May 11, 2012 6:54 am
Location: Soham, Cambridgeshire
Contact: Website

Re: Problems with handling "socket.gaierror"

Mon Feb 11, 2013 2:55 pm

thanks for that dude! works!
Click here for my unofficial YouTube Channel > http://goo.gl/oFYBD

Return to “Python”