How to get the IP address in Python

0 min read 81 words

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:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags