Skip to content

Instantly share code, notes, and snippets.

@fossilet
Forked from zhasm/getip.py
Created September 19, 2012 04:02
Show Gist options
  • Save fossilet/3747618 to your computer and use it in GitHub Desktop.
Save fossilet/3747618 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
"""Get the local IP and Public IP"""
import re
from subprocess import Popen, PIPE
from threading import Lock
print_lock = Lock()
def localIPs():
p = Popen('sudo ifconfig', shell=True, stdout=PIPE)
lines = p.communicate()[0].splitlines()
ip_pat = r'\b(?:\d{1,3}\.){3}\d{1,3}\b'
ret = []
for line in lines:
try:
ret.append(re.findall(ip_pat, 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 = Popen('curl -s ifconfig.me/ip', shell=True, stdout=PIPE)
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