Get local IP in Python


This is a cool code snippet I have used on several occacions for Python projects that need to figure out what the IP of the device they are running on is.
import socket
import fcntl
import struct


def get_ip_address(ifname):

    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915, # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

ip_address = get_ip_address('wlan0')

print(ip_address)