zhasm
7/31/2012 - 9:52 AM

Get the local IP and Public IP

Get the local IP and Public IP

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
#
# author  : Rex Zhang
# datetime: 2012-07-31 16:48:38
# filename: ip.py

"""Get the local IP and Public IP"""

import re
from threading import Lock

print_lock=Lock()

def bashOutput(cmd):
    import subprocess
    if ' ' in cmd:
        cmd=cmd.split()
    else:
        cmd=[cmd,]
    return subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]

def localIPs():
    lines=bashOutput('sudo ifconfig').splitlines()
    regex=r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
    ret=[]
    for line in lines:
        try:
            ret.append(re.findall(regex, line)[0])
        except:
            pass
    if '127.0.0.1' in ret:
        ret.remove('127.0.0.1')

    with print_lock:
        if ret:
            print "Local IPs:\t", "\t".join(sorted(ret))
        else:
            print "No local IP."

def publicIP():
    ret=bashOutput('curl -s ifconfig.me/ip')
    with print_lock:
        if ret:
            print "Public IP:\t", ret.strip()
        else:
            print "No Public IP."

def main():
    import threading
    threads= []
    functions=[publicIP, localIPs]

    for i in range(2):
        t=threading.Thread(target=functions[i])
        threads.append(t)
        t.start()


if __name__=='__main__':
    main()