| 1 |
# |
| 2 |
# Copyright (C) 2020 FreeIPA Contributors see COPYING for license |
| 3 |
# |
| 4 |
"""Get host's FQDN |
| 5 |
""" |
| 6 |
import socket |
| 7 |
|
| 8 |
|
| 9 |
def gethostfqdn(): |
| 10 |
"""Get the fully qualified domain name of current host from glibc |
| 11 |
|
| 12 |
This function may return an FQDN with up to MAXHOSTFQDNLEN characters |
| 13 |
(253). The effective hostname is still limited to MAXHOSTNAMELEN (64). |
| 14 |
|
| 15 |
:return: FQDN as str |
| 16 |
""" |
| 17 |
hostname = socket.gethostname() |
| 18 |
# this call can never fail except for misconfigured nsswitch.conf |
| 19 |
# without nss-myhostname provider. The myhostname provider translates |
| 20 |
# gethostname() to local interfaces. |
| 21 |
gai = socket.getaddrinfo( |
| 22 |
hostname, |
| 23 |
None, # service/port is irrelevant |
| 24 |
family=socket.AF_UNSPEC, # IPv4 or IPv6 |
| 25 |
type=socket.SOCK_DGRAM, # optimization, TCP/RAW gives same result |
| 26 |
# include canonical name in first addrinfo struct |
| 27 |
# only use address family when at least one non-local interface |
| 28 |
# is configured with that address family |
| 29 |
flags=socket.AI_CANONNAME | socket.AI_ADDRCONFIG |
| 30 |
) |
| 31 |
# first addrinfo struct, fourth field is canonical name |
| 32 |
# getaddrinfo() either raises an exception or returns at least one entry |
| 33 |
return gai[0][3] |