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 socket
import struct
import subprocess
import sys
import thread
from threading import Thread

View file

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