Get IP Addresses in Python

An Internet Protocol address (IP address) is a numerical label that is used to provide unique identifiers for devices on a network. In this tutorial, we will learn how to get the local IP address of the system in Python.


Get Local IP Address in Python using socket.gethostname()

We can use the Python socket package to get the local IP address of the system. First, get the hostname using socket.gethostname() and pass the result to socket.gethostbyname().


import socket



Get Primary System IP Address in Python using s.getsockname()

If the machine is connected to the internet we can get the primary system IP address using the socket.socket() and socket.getsockname() functions.


import socket

s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("", 80))



Get Primary IP Address Without Internet Connection

The example below provides the primary IP address of the system and works on NAT, public, private, external, and internal IP's.


import socket
def extract_ip():
   st = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
       st.connect(('', 1))
       IP = st.getsockname()[0]
   except Exception:
       IP = ''
   return IP