If interface is not specified, try to get external IP using ifconfig.co first

This commit is contained in:
Oleksii Shevchuk 2017-03-11 08:19:20 +02:00
parent 0497299528
commit 83323d10e3
1 changed files with 15 additions and 2 deletions

View File

@ -1,5 +1,8 @@
# -*- coding: UTF8 -*-
# -*- coding: utf-8 -*-
import netifaces
import urllib2
import netaddr
def get_local_ip(iface = None):
'''
Returns local ip address (no 127.0.0.1) or None
@ -8,11 +11,21 @@ def get_local_ip(iface = None):
if iface != None:
ifaces = [iface]
else:
ifaces = netifaces.interfaces()
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
opener.addheaders = [('User-agent', 'curl/7.50.0')]
try:
response = opener.open('http://ifconfig.co', timeout=5)
if response.code == 200:
return str(netaddr.IPAddress(response.read()))
except:
pass
for anInt in ifaces:
addr = netifaces.ifaddresses(anInt)[netifaces.AF_INET][0]['addr']
if addr != "127.0.0.1":
return addr
return None
except Exception:
return None