gethostbyname() function in Python

The gethostbyname() function of socket module returns the IP address of a given host name. The returned address is an IPv4 address.

socket Updated 2 Feb 2017 1 min read

Function Name

gethostbyname

Function Signature

gethostbyname(hostname)

Overview

  • Given a host name the gethostbyname() function returns the IP address of the host.

  • Unlike, gethostbyname() returns just one ip of the host even though the host could resolve to multiple IPs from a given location.

  • The returned IP address is an IPv4 address.

  • If the developer needs to resolve the hostname into IPv6 addresses or both IPv4 and IPv6 addresses are needed, socket.getaddrinfo() function can be used.

  • When the parameter hostname is omitted hostname defaults to localhost.

Parameters

hostname - The name of the host system for which IP address resolution is needed.

Return Value

The IPv4 address of the host name provided.

Example

python
import socket

hostName    = "example.org"

ipAddress   = socket.gethostbyname(hostName)

print("IP address of the host name {} is: {}".format(hostName, ipAddress))

Output

Output
IP address of the host name example.org is: 93.184.216.34