0

Background: I have always wanted to try my hand at scripting so here goes!

Problem: When gethostbyaddr gets to an IP with no DNS entry it errors and my script doesn't continue on.

Here is what I have so far:

import socket

file = 'ServerList'

f = open(file, 'r')

 lines = f.readlines()
 f.close()
 for i in lines:
    host = i.strip()
    if socket.gethostbyaddr(host) return(True):
        val1 = socket.gethostbyaddr(host)
        print("%s - %s" % (host, val1))
    else:
        print ("%s - No Entry" % (host))

But it errors probably because the return(True) is not proper syntax.

Can anyone help?

Thanks, J

J LE
  • 1

1 Answers1

2

As for basic syntax, you should remove the return(True) as mentioned by itzmeontv.

However, if the method fails it will most likely throw some kind of exception (I tried some servers and got a socket.gaierror), so you'll want to catch and handle those cases with try ... except:

import socket

file = 'ServerList'

f = open(file, 'r')

lines = f.readlines()
f.close()
for i in lines:
    host = i.strip()
    try:
        val1 = socket.gethostbyaddr(host)
        print("%s - %s" % (host, val1))
    except socket.error, exc:
        print ("%s - No Entry, socket error: %s" % (host, exc))

I recommend reading through Handling Exceptions.

Community
  • 1
  • 1
adrianus
  • 3,141
  • 1
  • 22
  • 41
  • But not with a bare `except:` - instead use `except socket.gaierror:` or something alike... – glglgl Jul 15 '15 at 06:43