ip address and host name

Used socket to get the ip address and host name. We kept the code inside try & except for exception handling.
import socket
try: 
        my_host = socket.gethostname() 
        my_ip = socket.gethostbyname(my_host) 
        print("Hostname :  ",my_host) 
        print("IP : ",my_ip) 
except: 
        print("Unable to get Hostname and IP address")
The output will change based on your hosting server.

getfqdn() to retrieve the fully qualified domain name.
import socket
print("Fully Qualified Domain Name:", socket.getfqdn())
Retrieve all IP addresses for a host using gethostbyname_ex().
import socket
print(socket.gethostbyname_ex(socket.gethostname()))

Use Case: Web Server Monitoring

When setting up or monitoring a web server, retrieving the hostname and IP address can be essential for debugging or configuring network settings. This can help in identifying server locations, resolving domain names, or diagnosing network issues during deployment.

Error Handling with socket

Handle common errors like socket.gaierror when network-related issues occur. For example, if the host can't be resolved, using a try-except block can prevent crashes:

import socket
try:
    print(socket.gethostbyname('invalid.host'))
except socket.gaierror as e:
    print(f"Error: {e}")

PHP Script to display IP address.
All Built in Functions in Python bin() complex()
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer