Get IP Addresses in Python

Get IP Addresses in Python

Shivam Arora Jul-09, 2021 Jun-02, 2021 Python Python Network
  1. Use the socket.gethostname() Function to Get the Local IP Address in Python
  2. Use the socket.getsockname() Funtion to Get the Local IP Address in Python
  3. Use the netifaces Module to Get the Local IP Address in Python

IP addresses are a sequence of digits starting from 0.0.0.0 till 255.255.255.255, with each number in the address ranges of 0 to 255. It can uniquely identify a device over a network.

In this article, we will get the local IP addresses using Python.

Use the socket.gethostname() Function to Get the Local IP Address in Python

We can use the socket module in Python to create network connections and send messages across the network.

The function gethostname() returns the system’s hostname under which Python is currently being executed.

For example,

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

Output:

192.168.0.118

Use the socket.getsockname() Funtion to Get the Local IP Address in Python

If the computer device has a route connected to the Internet, then we can use the getsockname() function. It returns the IP address and port in the form of a tuple.

See the code below.

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

Output:

192.168.0.112

This method returns the primary IP of the local machine i.e., the default route.

We can also use this function to create a user-defined function that does not need any routable internet access.

See the code below.

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())

Output:

192.168.0.112

The above method works on all interfaces. It also works with all public, private, external IPs. This method is efficient on Linux, Windows, and OSX.

Use the netifaces Module to Get the Local IP Address in Python

The netifaces module is used to provide information about the network interfaces and their status.

We can use it to get the local machine’s IP address as shown below.

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))

Output:

No IP addr
No IP addr
No IP addr
No IP addr
192.168.0.104
127.0.0.1

Related Article - Python Network

  • Python Get Hostname
  • Python Ping