Methods to Retrieve IP Addresses and Hostnames in a Local Network Using Python

Dec 11, 2025 · Programming · 12 views · 7.8

Keywords: Python | network scanning | IP addresses | hostnames | local network

Abstract: This article describes how to discover active devices in a local network using Python by determining the local IP address and netmask, calculating the network range, scanning active addresses, and performing DNS reverse lookup for hostnames. It covers core steps and supplementary methods such as using scapy or multiprocessing ping scans. Suitable for multi-platform environments.

Introduction

Retrieving a list of IP addresses and hostnames from a local network is a common task in network administration and programming. This article provides a comprehensive guide to accomplish this using Python, focusing on a method based on the accepted best answer.

Core Method: Determine and Scan Local Network

The core method involves five steps: determining the local IP address, netmask, network range, scanning active addresses, and performing DNS reverse lookup.

Step 1: Determine Local IP Address

To get the local IP address, use the socket library with a cross-platform approach.

import socket

def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.connect(("8.8.8.8", 80))
    ip = s.getsockname()[0]
    s.close()
    return ip

local_ip = get_local_ip()
print(f"Local IP: {local_ip}")

Step 2: Determine Netmask

Obtain the netmask using the netifaces library for portability.

import netifaces

def get_netmask(interface='default'):
    if interface == 'default':
        gateways = netifaces.gateways()
        default_gateway = gateways['default'][netifaces.AF_INET]
        interface = default_gateway[1]
    addrs = netifaces.ifaddresses(interface)[netifaces.AF_INET][0]
    return addrs['netmask']

netmask = get_netmask()
print(f"Netmask: {netmask}")

Step 3: Calculate Network Range

Calculate the network address and broadcast address with the IP and netmask.

import ipaddress

network = ipaddress.ip_network(f"{local_ip}/{netmask}", strict=False)
print(f"Network: {network.network_address}")
print(f"Broadcast: {network.broadcast_address}")
hosts = list(network.hosts())

Step 4: Scan Active IP Addresses

Use a multi-threaded ping scanner to find active IPs.

import subprocess
import threading
from queue import Queue

def ping_host(ip, queue):
    try:
        subprocess.check_call(['ping', '-c', '1', '-W', '1', ip], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
        queue.put(ip)
    except subprocess.CalledProcessError:
        pass

def scan_network(hosts):
    queue = Queue()
    threads = []
    for ip in hosts:
        thread = threading.Thread(target=ping_host, args=(str(ip), queue))
        thread.start()
        threads.append(thread)
    for thread in threads:
        thread.join()
    active_ips = []
    while not queue.empty():
        active_ips.append(queue.get())
    return active_ips

active_ips = scan_network(hosts)
print(f"Active IPs: {active_ips}")

Step 5: DNS Reverse Lookup

Perform DNS reverse lookup for each active IP to get hostnames.

def get_hostname(ip):
    try:
        hostname = socket.gethostbyaddr(ip)[0]
        return hostname
    except socket.herror:
        return None

for ip in active_ips:
    hostname = get_hostname(ip)
    print(f"IP: {ip}, Hostname: {hostname}")

Supplementary Methods

Other approaches include using scapy for ARP scanning or simple methods like the <code>arp -a</code> command.

Conclusion

This article presented a detailed method for retrieving IP addresses and hostnames in a local network using Python. The core method is robust and multi-platform.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.