Last modified: Apr 27, 2025 By Alexander Williams
Python: Get All IP Addresses on Local Network
Discovering all IP addresses on a local network is useful for network management. Python makes this task easy with its powerful libraries.
Table Of Contents
Why Find Local IP Addresses?
Knowing devices on your network helps with troubleshooting. It also aids in security monitoring and resource management.
Prerequisites
You need Python installed. Basic knowledge of networking concepts helps. We'll use the socket
and python-nmap
modules.
For more on networking, see our Subnet IP Address Using Python Guide.
Method 1: Using Socket Module
The socket
module comes with Python. It provides low-level networking interfaces.
import socket
def get_local_ip():
try:
# Create a socket connection
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
except Exception as e:
return str(e)
print("Local IP:", get_local_ip())
Local IP: 192.168.1.5
Method 2: Using Python-Nmap
Nmap is a powerful network scanner. The python-nmap
package provides Python bindings.
First, install the package:
pip install python-nmap
Then use this code to scan your network:
import nmap
def scan_network(network_range):
scanner = nmap.PortScanner()
scanner.scan(hosts=network_range, arguments='-sn')
hosts = []
for host in scanner.all_hosts():
if scanner[host].state() == 'up':
hosts.append(host)
return hosts
# Replace with your network range
network = "192.168.1.0/24"
print("Active IPs:", scan_network(network))
Active IPs: ['192.168.1.1', '192.168.1.5', '192.168.1.10']
Method 3: Using Netifaces
The netifaces
module provides network interface information. Install it first:
pip install netifaces
Here's how to use it:
import netifaces
def get_network_info():
interfaces = netifaces.interfaces()
for interface in interfaces:
addrs = netifaces.ifaddresses(interface)
if netifaces.AF_INET in addrs:
for addr_info in addrs[netifaces.AF_INET]:
print(f"{interface}: {addr_info['addr']}")
get_network_info()
eth0: 192.168.1.5
wlan0: 192.168.1.10
Important Considerations
Permissions matter: Some methods need admin rights. Run scripts with appropriate privileges.
Network size: Scanning large networks takes time. Be patient with bigger ranges.
For validating found IPs, check our Validate IPv4 and IPv6 Addresses in Python guide.
Error Handling
Network operations can fail. Always include error handling in your code.
Common errors include network timeouts and permission issues. Handle them gracefully.
For debugging Python errors, see our Fix TypeError: 'NoneType' Object Not Subscriptable guide.
Conclusion
Python offers multiple ways to find local IP addresses. Choose the method that fits your needs.
The socket
method is simplest. Nmap provides most features. Netifaces gives interface details.
Remember to use these tools responsibly. Only scan networks you have permission to access.