fully qualified hostname ?

Jonathan Giddy jon at rdt.monash.edu.au
Thu Aug 26 22:00:05 EDT 1999


Ted Horst <Ted.Horst at wdr.com> writes:
>> >
>> >What is the best way to get the fully qualified hostname in python (ie
>> >hostname.domainname) ?
>> >
>> >A portable solution would be ideal, but I would settle for Unix only.

Under Unix, I get the best (i.e. least surprising) results using the 
following gethostname function:


import socket

def getdnsnames(name):
    d = socket.gethostbyaddr(name)
    names = [ d[0] ] + d[1] + d[2]
    return names

def resolve(name):
    names = getdnsnames(name)
    for dnsname in names:
        if '.' in dnsname:
            fullname = dnsname
            break
    else:
        fullname = name
    return fullname

def gethostname():
    fullname = socket.gethostname()
    if '.' not in fullname:
        fullname = resolve(fullname)

    return fullname

--
jon at dstc.edu.au




More information about the Python-list mailing list