Last modified: Sep 13, 2026

Get Hostname from IP in Python

When working with network programming in Python, you often need to find the hostname associated with an IP address. This process is called reverse DNS lookup. Python provides built-in tools to accomplish this easily.

In this article, we'll explore how to get hostname from IP address using Python. We'll cover different approaches, common errors, and best practices for reliable results.

Understanding Reverse DNS Lookup

Before diving into code, let's understand what reverse DNS lookup means. Normally, DNS converts hostnames to IP addresses. Reverse DNS does the opposite - it converts IP addresses back to hostnames.

This functionality is essential for network diagnostics, security logging, and server management tasks where you need to identify which device or service corresponds to a particular IP address.

Using socket.gethostbyaddr() Method

The primary method for getting hostname from IP in Python is gethostbyaddr(). This function belongs to Python's socket module, which handles network operations.

The gethostbyaddr() function takes an IP address as input and returns a tuple containing three elements:

  • The hostname corresponding to the IP address
  • A list of aliases for the hostname
  • A list of IP addresses for the hostname
  • Basic Example

    Here's a simple example showing how to use gethostbyaddr():

    
    import socket
    
    # Define the IP address
    ip_address = "8.8.8.8"
    
    # Get hostname from IP address
    hostname_info = socket.gethostbyaddr(ip_address)
    
    # Display the result
    print("IP Address:", ip_address)
    print("Hostname:", hostname_info[0])
    print("Aliases:", hostname_info[1])
    print("IP Addresses:", hostname_info[2])
    

    When you run this code, you'll get output similar to:

    
    IP Address: 8.8.8.8
    Hostname: dns.google
    Aliases: []
    IP Addresses: ['8.8.8.8']
    

    In this example, we successfully retrieved the hostname "dns.google" for Google's public DNS server IP address 8.8.8.8.

    Handling Errors and Exceptions

    Not all IP addresses have associated hostnames. When reverse DNS lookup fails, Python raises a socket.herror exception. Always handle this case gracefully:

    
    import socket
    
    def get_hostname_from_ip(ip_address):
        """Safely retrieve hostname from IP address"""
        try:
            # Attempt reverse DNS lookup
            hostname_info = socket.gethostbyaddr(ip_address)
            return hostname_info[0]
        except socket.herror:
            # Handle case when no hostname exists
            return "No hostname found"
        except Exception as e:
            # Handle any other errors
            return f"Error: {str(e)}"
    
    # Test with different IP addresses
    test_ips = ["8.8.8.8", "1.1.1.1", "192.168.1.1"]
    
    for ip in test_ips:
        hostname = get_hostname_from_ip(ip)
        print(f"IP: {ip} -> Hostname: {hostname}")
    

    Sample output might look like:

    
    IP: 8.8.8.8 -> Hostname: dns.google
    IP: 1.1.1.1 -> Hostname: one.one.one.one
    IP: 192.168.1.1 -> Hostname: No hostname found
    

    Alternative Approaches

    While gethostbyaddr() is the standard approach, there are alternative methods depending on your specific requirements:

    Using socket.gethostbyaddr() with Local IPs

    For local network devices, reverse DNS might not be configured. In such cases, you can try getting the hostname directly:

    
    import socket
    
    # Try to get hostname for local IP
    local_ip = "192.168.1.1"
    
    try:
        hostname = socket.gethostbyaddr(local_ip)[0]
        print(f"Hostname for {local_ip}: {hostname}")
    except socket.herror:
        print(f"No reverse DNS entry for {local_ip}")
        # Fallback: try forward lookup
        try:
            hostname = socket.gethostname()
            print(f"Local machine hostname: {hostname}")
        except:
            print("Could not determine hostname")
    

    Important Considerations

    When implementing hostname lookup functionality, keep these points in mind:

    Network Dependency

    Reverse DNS lookup requires network connectivity. If your application runs in an isolated environment, these lookups will fail. Always implement proper error handling.

    Performance Impact

    DNS lookups introduce latency. For applications requiring fast responses, consider caching results or performing lookups asynchronously.

    IP Address Format

    Ensure you're passing valid IP addresses to gethostbyaddr(). Invalid formats will raise socket.gaierror:

    
    import socket
    
    # Valid IP address formats
    valid_ips = ["8.8.8.8", "2001:4860:4860::8888"]  # IPv4 and IPv6
    
    for ip in valid_ips:
        try:
            hostname_info = socket.gethostbyaddr(ip)
            print(f"{ip} resolves to {hostname_info[0]}")
        except socket.herror:
            print(f"No hostname for {ip}")
        except socket.gaierror:
            print(f"Invalid IP format: {ip}")
    

    Practical Applications

    Here are some real-world scenarios where hostname lookup proves valuable:

    Network Monitoring Tools

    When building network monitoring applications, you often log IP addresses. Converting these to hostnames makes logs more readable:

    
    import socket
    from datetime import datetime
    
    def log_connection_attempt(ip_address):
        """Log connection attempts with hostname information"""
        timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
        
        try:
            hostname = socket.gethostbyaddr(ip_address)[0]
            log_entry = f"[{timestamp}] Connection from {ip_address} ({hostname})"
        except socket.herror:
            log_entry = f"[{timestamp}] Connection from {ip_address} (No hostname)"
        
        print(log_entry)
        return log_entry
    
    # Example usage
    log_connection_attempt("8.8.8.8")
    log_connection_attempt("192.168.1.100")
    

    Output example:

    
    [2023-12-07 14:30:25] Connection from 8.8.8.8 (dns.google)
    [2023-12-07 14:30:26] Connection from 192.168.1.100 (No hostname)
    

    Conclusion

    Getting hostname from IP address in Python is straightforward using the socket.gethostbyaddr() method. This function provides valuable network information for diagnostics and logging purposes.

    Remember to always handle exceptions properly, especially socket.herror for missing reverse DNS entries. Consider performance implications for production applications and implement caching where appropriate.

    With the examples provided in this article, you can confidently implement hostname lookup functionality in your Python network applications. Whether you're building monitoring tools, security applications, or general network utilities, understanding how to perform reverse DNS lookups is an essential skill.

    Start with simple implementations and gradually add error handling and optimization features as needed. The socket module offers reliable, built-in functionality for all your hostname lookup needs.