Python Glossary Русский

Python 3.3+Linux · macOSsocketfunction

socket.sethostname()

names and addresses

Changes the machine's host name on Linux and macOS; administrator rights are required. Windows has no such function.

Syntax

socket.sethostname(name)

Without root (CAP_SYS_ADMIN) the call raises PermissionError. The name changes for the whole system (on Linux, for the current UTS namespace), not for the process, and only until reboot: the function does not touch /etc/hostname. Windows lacks the attribute entirely, so portable code checks hasattr(socket, 'sethostname').

Examples

import socket
print(hasattr(socket, 'sethostname'))  # → ? True на Unix, False на Windows
try:
    socket.sethostname('x' * 300)  # слишком длинное имя: откажут даже root
except OSError as e:
    print(type(e).__name__)  # → ? PermissionError без прав, OSError у root

See also

Common errors

Open in the full glossarydocs.python.orgReport an inaccuracy