0
0
PythonHow-ToBeginner · 3 min read

How to Get Hostname and IP Address in Python Easily

Use the socket module in Python to get the hostname with socket.gethostname() and the IP address with socket.gethostbyname(). This provides the current machine's network name and its IP address.
📐

Syntax

The socket module provides two main functions to get hostname and IP address:

  • socket.gethostname(): Returns the current machine's hostname as a string.
  • socket.gethostbyname(hostname): Returns the IPv4 address of the given hostname as a string.
python
import socket

hostname = socket.gethostname()
ip_address = socket.gethostbyname(hostname)

print("Hostname:", hostname)
print("IP Address:", ip_address)
💻

Example

This example shows how to get and print the current machine's hostname and IP address using the socket module.

python
import socket

# Get the hostname of the machine
hostname = socket.gethostname()

# Get the IP address of the hostname
ip_address = socket.gethostbyname(hostname)

print(f"Hostname: {hostname}")
print(f"IP Address: {ip_address}")
Output
Hostname: my-computer IP Address: 192.168.1.5
⚠️

Common Pitfalls

Sometimes socket.gethostbyname() returns 127.0.0.1 (localhost) instead of the real IP address. This happens if the hostname resolves to the loopback address. To get the actual IP address, you can create a dummy connection to an external server and check the socket's own address.

python
import socket

# Wrong way: may return 127.0.0.1
hostname = socket.gethostname()
ip = socket.gethostbyname(hostname)
print(f"IP from gethostbyname: {ip}")

# Better way: connect to an external host to get real IP
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
    s.connect(("8.8.8.8", 80))  # Google's DNS server
    ip = s.getsockname()[0]
finally:
    s.close()
print(f"Real IP address: {ip}")
Output
IP from gethostbyname: 127.0.0.1 Real IP address: 192.168.1.5
📊

Quick Reference

Summary of functions to get hostname and IP address:

FunctionDescription
socket.gethostname()Returns the current machine's hostname.
socket.gethostbyname(hostname)Returns the IPv4 address for the given hostname.
Socket connect methodUse a dummy UDP socket connection to get the real IP address if gethostbyname returns localhost.

Key Takeaways

Use socket.gethostname() to get your machine's hostname.
Use socket.gethostbyname() with the hostname to get the IP address.
If gethostbyname returns 127.0.0.1, use a dummy socket connection to find the real IP.
The socket module is built-in and requires no extra installation.
Always close sockets after use to avoid resource leaks.