File: fqdn.py

package info (click to toggle)
freeipa 4.12.4-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 100,668 kB
  • sloc: python: 298,952; javascript: 71,606; ansic: 49,369; sh: 6,547; makefile: 2,553; xml: 343; sed: 16
file content (33 lines) | stat: -rw-r--r-- 1,220 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#
# Copyright (C) 2020  FreeIPA Contributors see COPYING for license
#
"""Get host's FQDN
"""
import socket


def gethostfqdn():
    """Get the fully qualified domain name of current host from glibc

    This function may return an FQDN with up to MAXHOSTFQDNLEN characters
    (253). The effective hostname is still limited to MAXHOSTNAMELEN (64).

    :return: FQDN as str
    """
    hostname = socket.gethostname()
    # this call can never fail except for misconfigured nsswitch.conf
    # without nss-myhostname provider. The myhostname provider translates
    # gethostname() to local interfaces.
    gai = socket.getaddrinfo(
        hostname,
        None,  # service/port is irrelevant
        family=socket.AF_UNSPEC,  # IPv4 or IPv6
        type=socket.SOCK_DGRAM,  # optimization, TCP/RAW gives same result
        # include canonical name in first addrinfo struct
        # only use address family when at least one non-local interface
        # is configured with that address family
        flags=socket.AI_CANONNAME | socket.AI_ADDRCONFIG
    )
    # first addrinfo struct, fourth field is canonical name
    # getaddrinfo() either raises an exception or returns at least one entry
    return gai[0][3]