Finding hostname by IP Address

This blog uses gethostbyaddr() function in socket module to find hostname

gethostbyaddr() function takes IP Address and returns tuple contaning hostname, Alias list for the IP Address and IP Address of a host

Syntax
socket.gethostbyaddr(IP_Address)

Code : Asking user to input IP Address and finding the hostname.

Import socket module

import socket

Ask user to input IP Address

ip = input('Enter IP address to find its hostname: ')

Finding hostname using gethostbyaddr(). It uses try and except. It will display ‘Invalid IP’ for wrong IP entered

try:
    print(socket.gethostbyaddr(ip))
except socket.herror:
    print('IP Address not found')
except socket.gaierror:
    print('Invalid IP Address')

Output(Successfull)

Enter IP address to find its hostname: 8.8.8.8
('dns.google', [], ['8.8.8.8'])

Output(Loopback IP)

Enter IP address to find its hostname: 127.0.0.1
('DESKTOP-PL3FTLP', [], ['127.0.0.1'])

Output(Invalid IP)

Enter IP address to find its hostname: 56.36
Invalid IP Address

Output(IP not found)

Enter IP address to find its hostname: 192.168.1.1
IP Address not found

Advertisement

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s