0

using a simple code to get hostname from ip address.

#!/usr/bin/python
import socket
import os
import sys

try:
        fdes = open ("ip.txt","r")
        for line in fdes.readlines():
                print socket.gethostbyaddr(line)
except Exception:
        pass

e.g ip.txt have ip address:

10.10.1.10, 10.10.1.20, 10.10.1.30, 10.10.1.40, 10.10.1.50, 10.10.1.60, 10.10.1.70,

there is no hostname for 10.10.1.40, so the code breaks here, do not continue further, Error is "socket.herror:[errno 1] Unknown Host"

how i can forcefully ignore the error if a hostname is not available for as ip address ?

1
  • usually try/except surrounds one critical statement, if it fails all of its block are skipped. Commented Jan 15, 2014 at 15:05

2 Answers 2

2

This moves the hostname related code into the try/except block, while keeping the file reading stuff out of it; so if an exception is thrown your file reading code will still continue.

fdes = open("ip.txt","r")

for line in fdes.readlines():
    try:
        print socket.gethostbyaddr(line)
    except socket.error:
        pass

Note: this code only ignores socket.error exceptions while leaving all other exceptions unhandled (so a Ctrl+C which throws a KeyboardInterrupt will still stop the program).

Sign up to request clarification or add additional context in comments.

1 Comment

@Nabla true, but I try to keep my code as similar as possible to the OP's code.
1

Replace Exception in your code with socket.error:

try:
    # Do something with sockets that might throw an error
except socket.error:
    pass # Basically, ignore the error

This will ensure that you don't unintentionally ignore other errors in your code.

If you want to do something with the error, perhaps log it, use this code:

try:
    # Operation that might throw a socket error
except socket.error as e:
    print e
    # Do something with the error object

1 Comment

thanks, pardon my layman ship with scripting, what should i put here to replace # ONLY catch socket errors

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.