Skip to content

Instantly share code, notes, and snippets.

@zhanghui9700
Created April 21, 2014 07:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhanghui9700/11134906 to your computer and use it in GitHub Desktop.
Save zhanghui9700/11134906 to your computer and use it in GitHub Desktop.
packstack gen-answer-file get localhost ip
# -*- coding: utf-8 -*-
import re
import socket
def get_localhost_ip():
"""
Returns IP address of localhost.
"""
# TO-DO: Will probably need to find better way to find out localhost
# address.
# find nameservers
ns_regex = re.compile('nameserver\s*(?P<ns_ip>[\d\.\:]+)')
# 想让哪块网卡被default,修改/etc/resolv.conf即可。
rc, resolv = execute('cat /etc/resolv.conf | grep nameserver',
can_fail=False, use_shell=True, log=False)
nsrvs = []
for line in resolv.split('\n'):
match = ns_regex.match(line.strip())
if match:
nsrvs.append(match.group('ns_ip'))
# try to connect to nameservers and return own IP address
nsrvs.append('8.8.8.8') # default to google dns
for i in nsrvs:
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect((i, 0))
loc_ip = s.getsockname()[0]
except socket.error:
continue
else:
return loc_ip
raise NetworkError('Local IP address discovery failed. Please set '
'nameserver correctly.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment