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

print(socket.gethostbyname(socket.gethostname()))
192.168.1.67

 

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(("8.8.8.8", 80))

print(s.getsockname())
print(s.getsockname()[0])
192.168.1.67

 

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)
   try:      
       st.connect(('10.255.255.255', 1))
       IP = st.getsockname()[0]
   except Exception:
       IP = '127.0.0.1'
   finally:
       st.close()
   return IP
print(extract_ip())
192.168.1.67