ignore socket.error in python
Question: 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 ?


Answer: 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).

