Skip to Content

Get IP address with Python

Get IP address with Python

Today I got a new Ubuntu server. I tried to get its IP address with the ifconfig or ip commands.

I got a command not found error. I searched the errors on Google, and it looks like I need to install package to run these commands.

But I don’t have sudo access. Is there any other way to get the IP address without these commands?

You can try using Python. It is installed by default on most distributions. It is very easy to use.

>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0','eth1','eth2']
>>> ni.ifaddresses('eth0')
{17: [{'addr': '02:93:07:be:da:d9', 'broadcast': 'ff:ff:ff:ff:ff:ff'}], 2: [{'addr': '', 'netmask': '', 'broadcast': ''}], 10: [{'addr': 'fe80::93:7ff:febe:dad9%eth0', 'netmask': 'ffff:ffff:ffff:ffff::'}]}

In the above example, there are four interfaces lo, eth0, eth1, eth2. The ip address for eth0 is

A Linux server can have more than one network interface. You can check out my post on my website here to get more info about this.

This Python script displays the mac address, ip address, netmask for each network interface.

3 Easy Ways to Find IP address in Linux
3 Ways to fix ifconfig command not found in Linux

Here’s another way to get the IP address:

import socket
import fcntl
import struct

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])

get_ip_address('eth0')  # ''

You can refer to this post to get more about how to use Python to get ip address.


If you are simply a user on an Ubuntu server, and the administrator has disabled your access to certain tools, it may be difficult to determine which tools you have available. The ip command is typically available to end-users, but perhaps there’s a path issue (unlikely):

/usr/bin/ip addr show
# or
/bin/ip addr show
# or (could be restricted)
/sbin/ip addr show

Alternatively, you can try using curl to access an external service that will detect your public IP. There are quite a few out there – I just went with the first search result I found: