How to get all IP addresses in python?

kdiegorsantos at gmail.com kdiegorsantos at gmail.com
Wed Feb 24 20:14:44 EST 2016


On Friday, July 11, 2003 at 1:54:47 AM UTC-3, Yun Mao wrote:
> Hi. I did a little homework on google for this question. The answer was:
> >>> import socket
> >>> hostname = socket.gethostname()
> >>> ip = socket.gethostbyname(hostname)
> >>> print ip
> 192.168.55.101
> But what if I have several interfaces, say eth0, eth0:1, eth1, etc. How to
> get all of them? It would be a little undesirable if people suggest to parse
> the result of ifconfig because I in particular want the code to be cross
> platform. Thanks a lot!
> 
> Yun

import socket

def get_ipaddr():
    proc = subprocess.Popen(["ip addr show | egrep inet | awk '{{print $2}}' | awk -F'/' '{{print $1}}' | egrep -v '^127' | xargs'"],stdout=subprocess.PIPE, shell=True)
    x = proc.communicate()[0]
    return x.strip()



More information about the Python-list mailing list