Get all the external IP addresses of a host

The other questions aren't quite the same.

What I'm looking at achieving is a Python function which returns a list of all the IP addresses on a system, emulating the behaviour of:

ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'

Answers


You can use the subprocess python module to achieve this.

import subprocess
cmd = "ifconfig | grep 'inet addr:' | grep -v 127.0.0.1 | cut -d: -f2 | awk '{ print $1}'"
co = subprocess.Popen([cmd], shell = True, stdout = subprocess.PIPE)
ips = co.stdout.read().strip().split("\n")

That should give you a list of IP addresses.

PS : It'll be better to use the following command instead

ifconfig | grep inet | grep -v inet6 | grep -v 127.0.0.1 | awk '{print $2}' | cut -d\: -f2 | cut -d\  -f1

This will exclude IPV6 addresses if any.

Pure Python Way

If you are looking to do this entirely in Python, then checkout netifaces python module.


Need Your Help

How to compare large string integer values

c# string int

Currently I am working on a program that processes extremely large integernumbers .

Flask SqlAlchemy begin and end transaction

python flask-sqlalchemy

I'm writing a SqlAlchemy transaction in flask using sqlalchemy extension: