Skip to content

Instantly share code, notes, and snippets.

@bennr01
Created July 11, 2017 13:49
Show Gist options
  • Select an option

  • Save bennr01/7043a460155e8e763b3a9061c95faaa0 to your computer and use it in GitHub Desktop.

Select an option

Save bennr01/7043a460155e8e763b3a9061c95faaa0 to your computer and use it in GitHub Desktop.
python: check wether a hostname/IP refers to the localhost
"""
check if an ip address or hostname is local.
NOTE: IPv6 support is NOT 100% tested. Some IPv6 addresses seem to work, others not.
"""
import socket
def host_is_local(hostname, port=None):
"""returns True if the hostname points to the localhost, otherwise False."""
if port is None:
port = 22 # no port specified, lets just use the ssh port
hostname = socket.getfqdn(hostname)
if hostname in ("localhost", "0.0.0.0"):
return True
localhost = socket.gethostname()
localaddrs = socket.getaddrinfo(localhost, port)
targetaddrs = socket.getaddrinfo(hostname, port)
for (family, socktype, proto, canonname, sockaddr) in localaddrs:
for (rfamily, rsocktype, rproto, rcanonname, rsockaddr) in targetaddrs:
if rsockaddr[0] == sockaddr[0]:
return True
return False
if __name__ == "__main__":
i = raw_input("Please enter an hostname or IP: ")
il = host_is_local(i)
if il:
print "Hostname/IP is the localhost."
else:
print "Hostname/IP is not the localhost."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment