1

I wan to know the current IP address of my system. I am not able to find any solution for my device as of now. I have tried socket.gethostbyname(socket.gethostname()) approach, but it is returning me 127.0.0.1.

Is there any Python package to do so that will work well in both Ubuntu and Linux?

Georgy
  • 12,464
  • 7
  • 65
  • 73
tushar_ecmc
  • 186
  • 2
  • 21

2 Answers2

4

Keep in mind that your system can have multiple ip addresses, on many interfaces (this is especially true if you're working with containers or virtual machines), so you need to be explicit about which ip address you want.

Additionally, if your device is operating through a NAT of some sort, there may be an external address associated with your device that won't be visible on any of your interfaces.

So without some clarification in your question, it's hard to know exactly what you're looking for. For the purposes of this answer, I'm assuming you want "the first ip address on the interface associated with the default route". We can use the netifaces module to help with this:

First, we need the name of the default interface. We can use the netifaces.gateways() method to get a list of gateways:

>>> import netifaces
>>> netifaces.gateways()
{'default': {2: (u'192.168.1.1', u'eth0')}, 2: [(u'192.168.1.1', u'eth0', True)]}

The default key represents our default gateway, and the value of that keys is a dictionary where the keys are address families, so to get the interface name we need:

>>> netifaces.gateways()['default'][netifaces.AF_INET][1]
u'eth0'

Once we have the name of the default interface, we can look it up using the netifaces.interfaces() method:

>>> iface = netifaces.gateways()['default'][netifaces.AF_INET][1]
>>> netifaces.ifaddresses(iface)
{17: [{'broadcast': u'ff:ff:ff:ff:ff:ff', 'addr': u'64:00:6a:7d:06:1a'}], 2: [{'broadcast': u'192.168.1.255', 'netmask': u'255.255.255.0', 'addr': u'192.168.1.24'}, {'broadcast': u'192.168.1.100', 'netmask': u'255.255.255.0', 'addr': u'192.168.1.100'}, {'broadcast': u'192.168.1.101', 'netmask': u'255.255.255.0', 'addr': u'192.168.1.101'}], 10: [{'netmask': u'ffff:ffff:ffff:ffff::/64', 'addr': u'fe80::5da1:2401:a725:d2e0%eth0'}]}

That gets us a bunch of interface information, again keyed by address family. To get the first ip address of the interface:

>>> netifaces.ifaddresses(iface)[netifaces.AF_INET][0]['addr']
u'192.168.1.24'

And that is probably the value you're looking for.

larsks
  • 277,717
  • 41
  • 399
  • 399
1

You can make a bash call from Python:

import os
os.system('ipconfig')

or with subprocess

cmd = 'ipconfig'
results = subprocess.run(
           cmd, shell=True, universal_newlines=True, check=True)
print(results.stdout)
Petronella
  • 2,327
  • 1
  • 15
  • 24