How to get the IP address in Python

Python exposes a socket library that allows us to perform networking tasks such as getting the IP Address as well as getting the Hostname of our system.

import socket

try:
  host_name = socket.gethostname()
  host_ip = socket.gethostbyname(host_name)
  print(f"Hostname: {host_name}")
  print(f"IP : {host_ip}")
except:
  print("Could not get the IP Address or Hostname")

The above code imports the socket library and then runs a safe block of code.

We need to first get the hostname and then use that to get the IP Address.

Tags:
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments