Skip to content

Instantly share code, notes, and snippets.

@zhasm
Created July 31, 2012 09:52
Show Gist options
  • Save zhasm/3215623 to your computer and use it in GitHub Desktop.
Save zhasm/3215623 to your computer and use it in GitHub Desktop.

Revisions

  1. zhasm revised this gist Jul 31, 2012. 1 changed file with 14 additions and 9 deletions.
    23 changes: 14 additions & 9 deletions getip.py
    Original file line number Diff line number Diff line change
    @@ -8,6 +8,9 @@
    """Get the local IP and Public IP"""

    import re
    from threading import Lock

    print_lock=Lock()

    def bashOutput(cmd):
    import subprocess
    @@ -29,17 +32,19 @@ def localIPs():
    if '127.0.0.1' in ret:
    ret.remove('127.0.0.1')

    if ret:
    print "Local IPs:\t", "\t".join(sorted(ret))
    else:
    print "No local IP."
    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')
    if ret:
    print "Public IP:\t", ret.strip()
    else:
    print "No Public IP."
    with print_lock:
    if ret:
    print "Public IP:\t", ret.strip()
    else:
    print "No Public IP."

    def main():
    import threading
    @@ -53,4 +58,4 @@ def main():


    if __name__=='__main__':
    main()
    main()
  2. zhasm created this gist Jul 31, 2012.
    56 changes: 56 additions & 0 deletions getip.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,56 @@
    #!/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

    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')

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

    def publicIP():
    ret=bashOutput('curl -s ifconfig.me/ip')
    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()