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.

ifconfig

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

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(
            s.fileno(),
            0x8915,  # SIOCGIFADDR
            struct.pack('256s', network[:15])
        )[20:24])

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

Save the code above and name it ipaddress.py

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

from ipaddress import IPAddress

ipaddress = IPAddress()
print(ipaddress.get_ipaddress())

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

python demo.py

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