Finding local IP addresses using Python's stdlib

Here is a code snippet that uses the socket module from Python's standard library to find the local IP addresses of the host machine:

import socket

def get_local_ip():
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # doesn't even have to be reachable
        s.connect(('', 1))
        IP = s.getsockname()[0]
        IP = ''
    return IP


This code creates a socket and connects to a non-local address using the socket's connect method. Then it retrieves the socket's own address using getsockname() method, which returns a tuple containing the IP address and the port number.

Watch a course Python - The Practical Guide

Note that you may have multiple IP addresses, If you want to see all IP addresses use the socket.getaddrinfo() method.