Get IP Address of a Device using Python

The IP Address is a main element in the working of a communication network. Its main objective is to pass the information in a network. It helps find the destination of the data to be passed. Each device has its unique IP Address. Python language consists of many methods that help in problem-solving. To get an IP Address, you can use the socket() module of Python.

Using the socket module to get the IP Address

In Python, the socket() module deals with the connections in a network. It helps in communication between the client and server. This module provides functions such as creating a socket, connecting to a server, binding to an address, and many more. The below steps describe how to use the socket library to get the IP Address of a device.

  1. Importing the socket module
  2. Getting the hostname using the gethostname() method in the socket module
  3. Getting the IP Address using the gethostbyname() method based on the obtained hostname
  4. Printing the IP Address of the device
import socket
host_name = socket.gethostname()
ip_addr = socket.gethostbyname(host_name)
print(f"IP Address: {ip_addr}")

When we implement the above Python program, it shows the IP Address as an output.

OUTPUT
IP Address: 172.17.0.2

So, this is the way to obtain the IP Address of a device using Python language.

Leave a Comment

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

Scroll to Top