Hello,

While I was debugging some salt issues I dug into the python code and found a
piece of code in the `socket.py` module that surprised my a bit:

In the `getfqdn` function the `gethostbyaddr` name function is being called with
a `hostname` instead of an `ipaddress`:

```python
def getfqdn(name=''):
    """Get fully qualified domain name from name.
    An empty argument is interpreted as meaning the local host.
    First the hostname returned by gethostbyaddr() is checked, then
    possibly existing aliases. In case no FQDN is available, hostname
    from gethostname() is returned.
    """
    name = name.strip()
    if not name or name == '0.0.0.0':
        name = gethostname() # (1)
    try:
        hostname, aliases, ipaddrs = gethostbyaddr(name) # (2)
    except error:
        pass
    else:
        aliases.insert(0, hostname)
        for name in aliases:
            if '.' in name:
                break
        else:
            name = hostname
    return name
```

1. `gethostname()`:

The documentation states:

```
Return a string containing the hostname of the machine where the Python 
interpreter is currently executing.

If you want to know the current machine’s IP address, you may want to use 
gethostbyname(gethostname()).
```

2. `gethostbyaddr()`:

Also from the documentation:

```
Return a triple (hostname, aliaslist, ipaddrlist) where hostname is the primary 
host name responding to the *given ip_address* (...)
```

As the documentation states it expects an `ip_address` and not a hostname,
but it is given a `hostname` instead.

I used the following two snippets to check the different behaviors:

```
python -c 'import socket; 
print(socket.gethostbyaddr(socket.gethostbyname(socket.gethostname())))'
```

```
python -c 'import socket; print(socket.gethostbyaddr(socket.gethostname()))'
```

Now on *most* of my machines the results are exactly the same, but on some it
differs (which I actually attribute to strange `/etc/hosts` configurations).

On the other hand I feel given the documentation, passing the `ip_address` would
be the right thing to do, so I am wondering if I am missing something very
obvious here (especially given that the code seems to be unchanged for 18 
years).

Best regards,

Florian
-- 
https://mail.python.org/mailman/listinfo/python-list

Reply via email to