Reputation: 27816
I have a string host
which can be a hostname (without domain), ipv4 address or ipv6 address.
Is there a simple way to determine if this refers to localhost
loop-back device?
Python Version: 2.7
Upvotes: 6
Views: 5198
Reputation: 16624
You could check if IP address of the inputted host within loopback address block, 127.0.0.0/8
for IPv4, ::1
for IPv6:
import socket
import struct
def is_loopback(host):
loopback_checker = {
socket.AF_INET: lambda x: struct.unpack('!I', socket.inet_aton(x))[0] >> (32-8) == 127,
socket.AF_INET6: lambda x: x == '::1'
}
for family in (socket.AF_INET, socket.AF_INET6):
try:
r = socket.getaddrinfo(host, None, family, socket.SOCK_STREAM)
except socket.gaierror:
return False
for family, _, _, _, sockaddr in r:
if not loopback_checker[family](sockaddr[0]):
return False
return True
for host in ('localhost', 'alias-of-localhost', 'google.com'):
print host, is_loopback(host)
yields:
localhost True
alias-of-localhost True
google.com False
Update: there is a python2 backport of python3 ipaddress
library, you could replace checker part with checking against its .is_loopback
property, internal logic is the same.
Upvotes: 7
Reputation: 1807
try this on Unix:
import subprocess
hn = subprocess.Popen(['hostname'], stdout=subprocess.PIPE) hn_out = hn.stdout.readline().strip('\n')
if host == '127.0.0.1' or host == '::1' or host == hn_out: print("It's localhost")
Upvotes: 0