Advertisement
Jackspade9624

geoip

Jun 5th, 2025
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.72 KB | None | 0 0
  1. #!/bin/bash
  2.  
  3. # Function to display the help menu
  4. show_help() {
  5. echo "Usage: $0 [IP_ADDRESS]"
  6. echo " Retrieves geolocation information for a given IP address."
  7. echo ""
  8. echo "Options:"
  9. echo " -h, --help Show this help message and exit."
  10. echo ""
  11. echo "Examples:"
  12. echo " $0 8.8.8.8"
  13. echo " $0" # Gets the public IP address of the machine
  14. }
  15.  
  16. # Function to geolocate an IP address
  17. geolocate_ip() {
  18. local ip="$1"
  19. local api_url="http://ip-api.com/json/$ip"
  20.  
  21. # Fetch and parse the JSON data using curl and jq
  22. local response=$(curl -s "$api_url")
  23. local status=$(echo "$response" | jq -r '.status')
  24.  
  25. if [ "$status" == "success" ]; then
  26. local country=$(echo "$response" | jq -r '.country')
  27. local region=$(echo "$response" | jq -r '.regionName')
  28. local city=$(echo "$response" | jq -r '.city')
  29. local lat=$(echo "$response" | jq -r '.lat')
  30. local lon=$(echo "$response" | jq -r '.lon')
  31. local isp=$(echo "$response" | jq -r '.isp')
  32.  
  33. echo "Geolocation Information for $ip:"
  34. echo " Country: $country"
  35. echo " Region: $region"
  36. echo " City: $city"
  37. echo " Latitude: $lat"
  38. echo " Longitude: $lon"
  39. echo " ISP: $isp"
  40. else
  41. echo "Error: Could not retrieve geolocation information for $ip."
  42. echo " Reason: $(echo "$response" | jq -r '.message')"
  43. fi
  44. }
  45.  
  46. # Main script logic
  47.  
  48. # Check for help option
  49. if [[ "$1" == "-h" || "$1" == "--help" ]]; then
  50. show_help
  51. exit 0
  52. fi
  53.  
  54. # Determine the IP address
  55. if [ -z "$1" ]; then
  56. # If no IP address is provided, get the public IP address
  57. ip=$(curl -s ipinfo.io/ip)
  58. else
  59. # Use the provided IP address
  60. ip="$1"
  61. fi
  62.  
  63. # Geolocate the IP address
  64. geolocate_ip "$ip"
  65.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement