How to get the local IP address of your Raspberry Pi from Python?

When working on a Raspberry Pi, is essential to know the local IP address in order to SSH or SFTP into the device.  You can do that from the terminal using the following command.


Look under wlan0 if you are connected using Wifi. Then look for the IP address under inet addr:

If you need to get the IP address from inside your Python script, you can use the following code.

import socket
import fcntl
import struct

class IPAddress():
    def __init__(self):
        print("Initalize IPAddress")

    def get_interface_ipaddress(self, network):
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        return socket.inet_ntoa(fcntl.ioctl(
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', network[:15])

    def get_ipaddress(self, network='wlan0'):
        return self.get_interface_ipaddress(network)

Save the code above and name it

Next, create a new file and copy and paste the following sample code.

from ipaddress import IPAddress

ipaddress = IPAddress()

Save the sample code above and name it Then run it from terminal as follow:


If you need help, leave me a comment below and I will get back to you as soon as possible.