gethostname() function in Python

The python function gethostname(), returns the host name of the system under which the python interpreter is executed.

socket Updated 2 Feb 2017 1 min read

Function Name

gethostname

Function Signature

socket.gethostname()

Overview

  • The Python function socket.gethostname() returns the host name of the current system under which the Python interpreter is executed.

  • This Python function can be combined with socket.gethostbyname()to get the IP address of the local host.

Parameters

None

Return Value

Host name of the localhost is returned.

Python Example using gethostname()

python
# sample python program for gethostname

import socket

# Get the local host name

myHostName = socket.gethostname()

print("Name of the localhost is {}".format(myHostName))

# Get the IP address of the local host

myIP = socket.gethostbyname(myHostName)

print("IP address of the localhost is {}".format(myIP))

Output of Python Example using gethostname

Output
Name of the localhost is mysystem.local

IP address of the localhost is 192.168.1.201