baqarhussain's picture
Update app.py
29238ba verified
import streamlit as st
import socket
import requests
import pycountry
from urllib.parse import urlparse
# Function to extract the domain name from the URL
def get_domain(url):
parsed_url = urlparse(url)
# Return only the hostname (e.g., google.com)
return parsed_url.netloc if parsed_url.netloc else parsed_url.path
# Function to get the IP address of a given URL
def get_ip_address(url):
try:
domain = get_domain(url) # Extract domain from URL
ip = socket.gethostbyname(domain) # Resolve IP address
return ip
except socket.gaierror:
return None
# Function to get the country info from the IP address using ipinfo.io
def get_country_info(ip):
try:
# Requesting country info from ipinfo.io API
response = requests.get(f"https://ipinfo.io/{ip}/json")
data = response.json()
country_name = data.get("country", "Unknown")
return country_name
except requests.exceptions.RequestException as e:
st.error(f"Error: {e}")
return None
# Function to get the flag URL from a country code
def get_country_flag(country_name):
try:
# Using pycountry to get the alpha_2 country code (e.g., "US", "IN")
country = pycountry.countries.get(name=country_name)
if country:
country_code = country.alpha_2
flag_url = f"https://countryflagsapi.com/png/{country_code.lower()}"
return flag_url
else:
return "https://countryflagsapi.com/png/unknown" # Default flag if country not found
except AttributeError:
return "https://countryflagsapi.com/png/unknown" # Return unknown flag if error
# Streamlit app
def main():
st.title("Website IP and Country Info Finder")
# Input field for the URL
url = st.text_input("Enter the URL of the website:")
# Button to fetch information
if st.button("Submit"):
if url:
ip_address = get_ip_address(url)
if ip_address:
country_name = get_country_info(ip_address)
if country_name:
st.success(f"IP Address: {ip_address}")
st.success(f"Country: {country_name}")
flag_url = get_country_flag(country_name)
st.image(flag_url, caption=f"Flag of {country_name}", width=100)
else:
st.error("Could not retrieve country information.")
else:
st.error("Could not resolve IP address from the given URL.")
else:
st.error("Please enter a valid URL.")
if __name__ == "__main__":
main()