How to Get the IP Address in Python


If you need to get the IP Address in your Python application, then you can do the following:

Option 1 – Using socket.gethostname()

import socket
print(socket.gethostbyname(socket.gethostname()))

Option 2 – Using socket.getsockname()

import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
print(s.getsockname()[0])

Option 3 – Using the netifaces module

from netifaces import interfaces, ifaddresses, AF_INET
for ifaceName in interfaces():
    addresses = [i['addr'] for i in ifaddresses(ifaceName).setdefault(AF_INET, [{'addr':'No IP addr'}] )]
    print(' '.join(addresses))