Skip to content

Instantly share code, notes, and snippets.

@ziadsawalha
Last active August 29, 2015 13:57
Show Gist options
  • Save ziadsawalha/9657896 to your computer and use it in GitHub Desktop.
Save ziadsawalha/9657896 to your computer and use it in GitHub Desktop.
Get local ip addresses
import socket
def get_local_ips():
"""Return local ipaddress(es)."""
list1 = []
list2 = []
defaults = ["127.0.0.1", r"fe80::1%lo0"]
hostname = None
try:
hostname = socket.gethostname()
except Exception as exc:
LOG.debug("Error in gethostbyname_ex: %s", exc)
try:
_, _, addresses = socket.gethostbyname_ex(hostname)
list1 = [ip for ip in addresses]
except Exception as exc:
LOG.debug("Error in gethostbyname_ex: %s", exc)
try:
list2 = [info[4][0] for info in socket.getaddrinfo(hostname, None)]
except Exception as exc:
LOG.debug("Error in getaddrinfo: %s", exc)
return list(set(list1 + list2 + defaults))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment