always use ip/route to detect local ipv4

This commit is contained in:
j 2014-05-23 13:22:30 +02:00
parent d2bec145fa
commit d787cec8e2
2 changed files with 22 additions and 24 deletions

View file

@ -6,8 +6,6 @@ import json
import logging import logging
import socket import socket
import struct import struct
import subprocess
import sys
import thread import thread
from threading import Thread from threading import Thread

View file

@ -138,30 +138,30 @@ def get_interface():
return interface return interface
def get_local_ipv4(): def get_local_ipv4():
ip = socket.gethostbyaddr(socket.getfqdn())[-1][0] if sys.platform == 'darwin':
if ip == '127.0.0.1': cmd = ['/sbin/route', '-n', 'get', 'default']
if sys.platform == 'linux2': p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
cmd = ['ip', 'route', 'show'] stdout, stderr = p.communicate()
interface = [[p.strip() for p in s.split(':', 1)]
for s in stdout.strip().split('\n') if 'interface' in s]
if interface:
interface = interface[0][1]
cmd = ['ifconfig', interface]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE) p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout, stderr = p.communicate() stdout, stderr = p.communicate()
local = [l for l in stdout.split('\n') if 'default' in l] ips = [l for l in stdout.split('\n') if 'inet ' in l]
if local: if ips:
dev = local[0].split(' ')[4] ip = ips[0].strip().split(' ')[1]
local_ip = [l for l in stdout.split('\n') if dev in l and not 'default' in l] else:
return [p for p in local_ip[0].split(' ')[1:] if '.' in p][0] cmd = ['ip', 'route', 'show']
else: p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
cmd = ['/sbin/route', '-n', 'get', 'default'] stdout, stderr = p.communicate()
p = subprocess.Popen(cmd, stdout=subprocess.PIPE) local = [l for l in stdout.split('\n') if 'default' in l]
stdout, stderr = p.communicate() if local:
interface = [[p.strip() for p in s.split(':', 1)] for s in stdout.strip().split('\n') if 'interface' in s] dev = local[0].split(' ')[4]
if interface: local_ip = [l for l in stdout.split('\n')
interface = interface[0][1] if dev in l and not 'default' in l]
cmd = ['ifconfig', interface] ip = [p for p in local_ip[0].split(' ')[1:] if '.' in p][0]
p = subprocess.Popen(cmd, stdout=subprocess.PIPE)
stdout, stderr = p.communicate()
ips = [l for l in stdout.split('\n') if 'inet ' in l]
if ips:
ip = ips[0].strip().split(' ')[1]
return ip return ip
def update_dict(root, data): def update_dict(root, data):