def ip_details(ipaddr): "Return IP type and country for an IP address" try: country_code = '' country_name = '' hostname = '' iptype = IP(ipaddr).iptype() if (iptype != "LOOPBACK" and ipaddr != '127.0.0.1' and iptype != "LINKLOCAL"): socket.setdefaulttimeout(60) #hostname = socket.gethostbyaddr(ipaddr)[0] hostname = get_hostname(ipaddr) if iptype != "PRIVATE": country_name, country_code = geoip_lookup(ipaddr) elif iptype == "LINKLOCAL": hostname = _('IPv6 Link local address') except (socket.gaierror, socket.timeout, socket.error, ValueError): if 'iptype' in locals() and iptype == "PRIVATE": hostname = _("RFC1918 Private address") else: hostname = _("Reverse lookup failed") finally: details = dict(ip_address=ipaddr, hostname=hostname or literal('unknown'), country_code=country_code or 'unknown', country_name=country_name or '', media_url=media_url()) return details
def country_flag(value): "return country flag" value = value.strip() try: IP(value).version() cname, ccode = geoip_lookup(value) if not ccode: ccode = 'unknown' tag = media_url() + url('flag', country=ccode) return image(tag, cname, title=cname) except ValueError: return ''