guettli
guettli

Reputation: 27816

Determine if host is localhost

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

Answers (2)

georgexsh
georgexsh

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

AnythingIsFine
AnythingIsFine

Reputation: 1807

try this on Unix:

you need the subprocess module to find out the local hostname

import subprocess

hn = subprocess.Popen(['hostname'], stdout=subprocess.PIPE) hn_out = hn.stdout.readline().strip('\n')

Test if "host" string is the IPv4 loop back address, IPv6 loop back address or if it's the local host name

if host == '127.0.0.1' or host == '::1' or host == hn_out: print("It's localhost")

Upvotes: 0

Related Questions