Python socket.gethostbyaddr(ip)

Question:

Trying to get a host name from lists of IP’s and Hostnames – I’m not getting the desired return when it parses through the IP addresses, it still just returns an IP.

example: 192.10.20.1
ouput: Found hostname 192.10.20.1 instead of converting it to the hostname.

def reverse_dns(IP):
    try:
        socket.gethostbyaddr(IP)
        print ('Found hostname', IP)
        return (True)
    except socket.error :
        print (IP)
        return (False)

def get_hostname (x) :
    hostname= []

    device = 'is blank'
    for device in x : 
        if reverse_dns(device) :
            hostname.append(device)
    return (hostname)

df['hostname'] = df['ips'].apply(get_hostname)
Asked By: Calarian

||

Answers:

You need to return the hostname that’s returned by gethostbyaddr(). Then

def reverse_dns(IP):
    try:
        hostname, aliaslist, ipaddrlist = socket.gethostbyaddr(IP)
        print ('Found hostname', IP)
        return hostname
    except socket.error :
        print (IP)
        return (False)

def get_hostname (x) :
    hostname= []

    for device in x : 
        hostname.append(reverse_dns(device) or 'is blank')
    return (hostname)

df['ips'] = df['hostname'].apply(get_hostname)
Answered By: Barmar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.