Advertisement
Python253

get_ip

May 13th, 2024
791
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.87 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. # Filename: get_ip.py
  4. # Version: 1.0.0
  5. # Author: Jeoi Reqi
  6.  
  7. """
  8. This script will return the local and public IP addresses of the machine.
  9.  
  10. Requirements:
  11.    - Python 3.x
  12.    - requests library
  13.  
  14. Functions:
  15.    - line: Draws a separation line in the console output.
  16.    - get_local_IP: Retrieves and prints the local IP address from socket.
  17.    - get_public_IP: Retrieves and prints the public IP address from an external service.
  18.  
  19. Usage:
  20.    - Run the script using the python command:
  21.          
  22.               'python get_ip.py'
  23.  
  24. Additional Notes:
  25.    - Ensure you have an active internet connection for retrieving the public IP address.
  26. """
  27.  
  28. import socket
  29. import requests
  30.  
  31. # Function to draw a separation line
  32. def line():
  33.     print("-" * 40)
  34.  
  35. line()
  36. print("Gathering Local & Public IP Addresses...")
  37. line()
  38.  
  39. # Function to get Local IP
  40. def get_local_IP():
  41.     try:
  42.         host_name = socket.gethostname()
  43.         local_ip = socket.gethostbyname(host_name)
  44.         print("\nLocal IP:\n    ", local_ip)
  45.     except socket.gaierror as e:
  46.         print("\nUnable to get Local IP! Socket error occurred.\nError:", e)
  47.     except Exception as e:
  48.         print("\nUnable to get Local IP!\nError:", e)
  49.  
  50. # Function to get Public IP from http://www.icanhazip.com
  51. def get_public_IP():
  52.     try:
  53.         response = requests.get("http://www.icanhazip.com")
  54.         response.raise_for_status()  # Check if the request was successful
  55.         public_ip = response.text.strip()
  56.         print("\nPublic IP:\n    ", public_ip)
  57.         line()
  58.     except requests.RequestException as e:
  59.         print("\nUnable to get Public IP! Request error occurred.\nError:", e)
  60.     except Exception as e:
  61.         print("\nUnable to get Public IP!\nError:", e)
  62.  
  63. # Return results
  64. print("RESULTS:")
  65. line()
  66. get_local_IP()
  67. get_public_IP()
  68.  
  69.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement