1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| import re
import subprocess
# https://stackoverflow.com/a/28532296
def is_ip_private(ip):
# https://en.wikipedia.org/wiki/Private_network
priv_lo = re.compile("^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
priv_24 = re.compile("^10\.\d{1,3}\.\d{1,3}\.\d{1,3}$")
priv_20 = re.compile("^192\.168\.\d{1,3}.\d{1,3}$")
priv_16 = re.compile("^172.(1[6-9]|2[0-9]|3[0-1]).[0-9]{1,3}.[0-9]{1,3}$")
res = priv_lo.match(ip) or priv_24.match(ip) or priv_20.match(ip) or priv_16.match(ip)
return res is not None
def get_local_ip_by_hostname():
process=subprocess.Popen(['hostname', '-I'], stdout=subprocess.PIPE)
ips, error = process.communicate()
if error != None:
return "127.0.0.1"
for ip in ips.split(" ")[:-1]:
if not is_ip_private(ip):
return ip
return "127.0.0.1"
|