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.
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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment