DEV Community

howtouselinux
howtouselinux

Posted on

 

Get the ip address in Ubuntu without ifconfig or ip command

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

But 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?

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

$python
>>> 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': '10.0.0.76', 'netmask': '255.255.255.0', 'broadcast': '10.0.0.255'}], 10: [{'addr': 'fe80::93:7ff:febe:dad9%eth0', 'netmask': 'ffff:ffff:ffff:ffff::'}]}

Enter fullscreen mode Exit fullscreen mode

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

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.

Related:

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 without using a python package:

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(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])

get_ip_address('eth0')  # '192.168.0.110'

Enter fullscreen mode Exit fullscreen mode

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

Answer2

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

Enter fullscreen mode Exit fullscreen mode

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:

curl ifconfig.me/all
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Advice For Junior Developers

Advice from a career of 15+ years for new and beginner developers just getting started on their journey.