def local_ip():
"""
Retrieve the first ip from the interface linked to the default route
:return str
"""
sys_name = system()
if sys_name == 'Darwin':
# OSX
route = Command('route')
ifconfig = Command('ifconfig')
iface = [
line.strip()
for line in route('-n', 'get', 'default')
if line.strip().startswith('interface')
][0].split(':')[1].strip()
return [
line.strip()
for line in ifconfig(iface)
if line.strip().startswith('inet ')
][0].split(' ')[1]
elif sys_name == 'Linux':
try:
ip = Command('ip')
iface = [
line.strip()
for line in ip('route')
if line.strip().startswith('default ')
][0].split(' ')[4]
except CommandNotFound:
route = Command('route')
iface = [
line.strip()
for line in route('-n')
if line.startswith('0.0.0.0')
][0].split(' ').pop()
try:
# try with IP
ip = Command('ip')
return [
line.strip()
for line in ip('addr', 'show', iface)
if line.strip().startswith('inet ')
][0].split(' ')[1].split('/')[0]
except CommandNotFound:
pass
# fallback to ifconfig
ifconfig = Command('ifconfig')
return [
line.strip()
for line in ifconfig(iface)
if line.strip().startswith('inet ')
][0].split(' ')[1]
return None
评论列表
文章目录