Get local IP address with Python
Using socket module
import socket
def public_ip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('8.8.8.8', 80))
ip = s.getsockname()[0]
finally:
s.close()
return ip
if __name__ == "__main__":
public_ip()
Using the os module
The os module in Python provides a way to interact with the operating system. We can use the os.popen()
method to execute a command in the command prompt and get the output.
import os
cmd = "ipconfig | findstr IPv4"
output = os.popen(cmd).read()
print(output)
In this example, we execute the ipconfig
command and use the findstr
command to search for the IPv4 address. The os.popen()
method returns the output of the command, which we then print out.
Using the netifaces module
Another way to get the local IP address of a computer is by using the netifaces module. This module provides a way to retrieve network interface information such as IP addresses, netmasks, and more.
import netifaces
interfaces = netifaces.interfaces()
for interface in interfaces:
if interface == 'lo':
continue
iface = netifaces.ifaddresses(interface).get(netifaces.AF_INET)
if iface != None:
for link in iface:
print(link['addr'])
The netifaces.interfaces()
method returns a list of all available network interfaces on the computer. We loop through each interface and check if it’s not the loopback interface (‘lo’). We then use the netifaces.ifaddresses()
method to get the IP address of the interface and print it out.
Back to Table of Contents
Disclaimer
- License under
CC BY-NC 4.0
- Copyright issue feedback
me#imzye.com
, replace # with @ - Not all the commands and scripts are tested in production environment, use at your own risk
- No personal information is collected.
Feedback