Skip to content

Instantly share code, notes, and snippets.

@seanthegeek
Last active August 8, 2024 15:29
Show Gist options
  • Save seanthegeek/893b9e8b7467fd1c993aa502d6eac242 to your computer and use it in GitHub Desktop.
Save seanthegeek/893b9e8b7467fd1c993aa502d6eac242 to your computer and use it in GitHub Desktop.
Gathering IP useful IP address info
# Requires flask and user_agents
import user_agents
from flask import request
def get_source_ip_address():
forwarded_header = request.headers.get("X-Forwarded-For")
if forwarded_header:
return forwarded_header.split(",")[0]
else:
return request.remote_addr
def get_source_device():
raw_user_agent = request.headers.get('User-Agent')
return user_agents.parse(raw_user_agent)
# Requires ipaddress
import ipaddress
def get_ip_addresses_from_cidr(cidr):
"""Returns a list of IP addresses from a CIDR notation"""
return [str(ip) for ip in ipaddress.ip_network(cidr, strict=False).hosts()]
# Requires ipwhois and geocoder
from ipwhois import IPWhois
import geocoder
def get_ip_whois(ip_address):
"""Gets whois information about an IP address"""
ip_address = str(ip_address).split("/")[0]
# https://ipwhois.readthedocs.io/en/latest/RDAP.html
# Pass asn_methods=[‘dns’, ‘http’] if your network blocks legacy WHOIS
response = IPWhois(ip_address).lookup_rdap(retry_count=1)
return response
def get_registrant_from_ip_whois(whois_data):
"""Returns the registrant name from parsed IP address whois data"""
try:
if whois_data["entities"] is None:
return None
entity = whois_data["entities"][0]
obj = whois_data["objects"][entity]
contact = obj["contact"]
return contact["name"]
except KeyError:
return None
def get_ip_address_info(ip_address):
"""Gets geolocation data from IPInfo IP address ownership from WHOIS/RDAP
(which avoids the need to get an IPinfo API key for ISP data)"""
ip_address_info = get_ip_whois(ip_address)
ip_address_info["ip_address"] = ip_address
ip_address_info["isp"] = get_registrant_from_ip_whois(ip_address_info)
geo = geocoder.ip(ip_address) # Uses ipinfo.io by default
ip_address_info["hostname"] = geo.hostname
ip_address_info["location"] = geo.address
ip_address_info["lat"] = geo.lat
ip_address_info["lng"] = geo.lng
return ip_address_info
# Requires dnspython
import dns.resolver
import dns.reversename
import dns.exception
def get_reverse_dns(ip_address):
try:
address = dns.reversename.from_address(ip_address)
hostname = str(dns.resolver.resolve(address, "PTR")[0]).rstrip(".")
except dns.exception.DNSException:
return None
return hostname
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment