How to Get the Hostname and Ipaddress Of a Machine Using Python

how to get machine information using python

To get started create a file called main.py and then import socket module as shown below.

import socket

Next, let’s create a function to extract the hostname and Ip address as shown below.

def info():
    hostname = socket.gethostname()
    ipaddress = socket.gethostbyname(hostname)
    print("Host name : ",hostname)
    print("IP address : ",ipaddress)

Now let’s finish by calling our main function.


if __name__ == "__main__":
    info()

Now open your terminal and run the command shown below.

python3 main.py

After running your program here are our results.

There you have it, Thanks for reading. Happy Coding

Leave a Comment

Your email address will not be published. Required fields are marked *