Skip to content

Get local IP address with Python


Using socket module

import socket

def public_ip():
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.connect(('', 80))
        ip = s.getsockname()[0]
    return ip

if __name__ == "__main__":

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()

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':
    iface = netifaces.ifaddresses(interface).get(netifaces.AF_INET)
    if iface != None:
        for link in iface:

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

  1. License under CC BY-NC 4.0
  2. Copyright issue feedback, replace # with @
  3. Not all the commands and scripts are tested in production environment, use at your own risk
  4. No personal information is collected.