📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Free IP lookup tool (#463)
Andrii Romasiun7cc80cf71c27
diff --git a/backend/apps/cloud/src/app.module.ts b/backend/apps/cloud/src/app.module.tsindex f3a9489d4..ba119adaa 100644--- a/backend/apps/cloud/src/app.module.ts+++ b/backend/apps/cloud/src/app.module.ts@@ -33,6 +33,7 @@ import { AppController } from './app.controller'import { isPrimaryNode, isPrimaryClusterNode } from './common/utils'import { OrganisationModule } from './organisation/organisation.module'import { RevenueModule } from './revenue/revenue.module'+import { ToolsModule } from './tools/tools.module'const modules = [SentryModule.forRoot(),@@ -90,6 +91,7 @@ const modules = [HealthModule,OrganisationModule,RevenueModule,+ ToolsModule,]@Module({diff --git a/backend/apps/cloud/src/common/utils.ts b/backend/apps/cloud/src/common/utils.tsindex f4ff0ed78..42608021e 100644--- a/backend/apps/cloud/src/common/utils.ts+++ b/backend/apps/cloud/src/common/utils.ts@@ -313,6 +313,54 @@ export const getGeoDetails = (ip: string, tz?: string): IPGeoDetails => {}}+export interface ExtendedGeoDetails {+ country: string | null+ countryName: string | null+ city: string | null+ region: string | null+ regionCode: string | null+ continentCode: string | null+ continentName: string | null+ postalCode: string | null+ latitude: number | null+ longitude: number | null+ timezone: string | null+}++export const getExtendedGeoDetails = (ip: string): ExtendedGeoDetails => {+ const data = lookup.get(ip)++ if (!data) {+ return {+ country: null,+ countryName: null,+ city: null,+ region: null,+ regionCode: null,+ continentCode: null,+ continentName: null,+ postalCode: null,+ latitude: null,+ longitude: null,+ timezone: null,+ }+ }++ return {+ country: data.country?.iso_code || null,+ countryName: data.country?.names?.en || null,+ city: data.city?.names?.en || null,+ region: data.subdivisions?.[0]?.names?.en || null,+ regionCode: data.subdivisions?.[0]?.iso_code || null,+ continentCode: data.continent?.code || null,+ continentName: data.continent?.names?.en || null,+ postalCode: data.postal?.code || null,+ latitude: data.location?.latitude || null,+ longitude: data.location?.longitude || null,+ timezone: data.location?.time_zone || null,+ }+}+const normalise = (raw: unknown): string | null => {if (!raw) return nullconst str = String(raw)diff --git a/backend/apps/cloud/src/tools/dto/ip-lookup.dto.ts b/backend/apps/cloud/src/tools/dto/ip-lookup.dto.tsnew file mode 100644index 000000000..b3170e016--- /dev/null+++ b/backend/apps/cloud/src/tools/dto/ip-lookup.dto.ts@@ -0,0 +1,56 @@+import { ApiProperty, ApiPropertyOptional } from '@nestjs/swagger'+import { IsOptional, IsString } from 'class-validator'++export class IpLookupQueryDto {+ @ApiPropertyOptional({+ description: 'IP address to look up. If not provided, uses the request IP.',+ example: '8.8.8.8',+ })+ @IsOptional()+ @IsString()+ ip?: string+}++export class IpLookupResponseDto {+ @ApiProperty({ description: 'The IP address that was looked up' })+ ip: string++ @ApiPropertyOptional({ description: 'Country ISO-3166 alpha-2 code' })+ country: string | null++ @ApiPropertyOptional({ description: 'Country name' })+ countryName: string | null++ @ApiPropertyOptional({ description: 'City name' })+ city: string | null++ @ApiPropertyOptional({ description: 'State/Province/Region name' })+ region: string | null++ @ApiPropertyOptional({ description: 'State/Province ISO-3166-2 code' })+ regionCode: string | null++ @ApiPropertyOptional({ description: 'Continent code' })+ continentCode: string | null++ @ApiPropertyOptional({ description: 'Continent name' })+ continentName: string | null++ @ApiPropertyOptional({ description: 'Postal/ZIP code' })+ postalCode: string | null++ @ApiPropertyOptional({ description: 'Latitude coordinate' })+ latitude: number | null++ @ApiPropertyOptional({ description: 'Longitude coordinate' })+ longitude: number | null++ @ApiPropertyOptional({ description: 'Timezone (IANA format)' })+ timezone: string | null++ @ApiPropertyOptional({ description: 'Whether the country is in the EU' })+ isInEuropeanUnion: boolean++ @ApiPropertyOptional({ description: 'IP version (4 or 6)' })+ ipVersion: 4 | 6+}diff --git a/backend/apps/cloud/src/tools/tools.controller.ts b/backend/apps/cloud/src/tools/tools.controller.tsnew file mode 100644index 000000000..a0372f6f0--- /dev/null+++ b/backend/apps/cloud/src/tools/tools.controller.ts@@ -0,0 +1,83 @@+import {+ BadRequestException,+ Controller,+ Get,+ Headers,+ Ip,+ Query,+} from '@nestjs/common'+import { ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger'+import net from 'net'++import { ToolsService } from './tools.service'+import { IpLookupQueryDto, IpLookupResponseDto } from './dto/ip-lookup.dto'+import { getIPFromHeaders, checkRateLimit } from '../common/utils'+import { trackCustom } from '../common/analytics'+import { Public } from '../auth/decorators'++const IP_LOOKUP_RL_REQUESTS = 30+const IP_LOOKUP_RL_TIMEOUT = 60 // 1 minute++@ApiTags('Tools')+@Controller('tools')+export class ToolsController {+ constructor(private readonly toolsService: ToolsService) {}++ @Get('ip-lookup')+ @Public()+ @ApiOperation({+ summary: 'Look up geolocation information for an IP address',+ description:+ 'Returns detailed geolocation data including country, city, region, coordinates, timezone, and more. If no IP is provided, uses the IP of the requester.',+ })+ @ApiResponse({+ status: 200,+ description: 'IP geolocation data',+ type: IpLookupResponseDto,+ })+ @ApiResponse({+ status: 400,+ description: 'Invalid IP address provided',+ })+ async lookupIP(+ @Query() query: IpLookupQueryDto,+ @Headers() headers: unknown,+ @Ip() reqIP: string,+ ): Promise<IpLookupResponseDto> {+ const clientIp = getIPFromHeaders(headers) || reqIP || ''+ const userAgent =+ typeof headers === 'object' && headers !== null+ ? (headers as Record<string, string>)['user-agent'] || ''+ : ''++ await checkRateLimit(+ clientIp,+ 'ip-lookup',+ IP_LOOKUP_RL_REQUESTS,+ IP_LOOKUP_RL_TIMEOUT,+ )++ let ip = query.ip || ''++ // Normalise IPv6 localhost+ if (ip === '::1' || ip === '::ffff:127.0.0.1') {+ ip = '127.0.0.1'+ }++ // Validate IP format+ if (!ip || !net.isIP(ip)) {+ throw new BadRequestException('Please enter a valid IP address')+ }++ const result = this.toolsService.lookupIP(ip)++ trackCustom(clientIp, userAgent, {+ ev: 'IP_LOOKUP',+ meta: {+ ipVersion: String(result.ipVersion),+ },+ })++ return result+ }+}diff --git a/backend/apps/cloud/src/tools/tools.module.ts b/backend/apps/cloud/src/tools/tools.module.tsnew file mode 100644index 000000000..fa8b9a7ac--- /dev/null+++ b/backend/apps/cloud/src/tools/tools.module.ts@@ -0,0 +1,10 @@+import { Module } from '@nestjs/common'+import { ToolsController } from './tools.controller'+import { ToolsService } from './tools.service'++@Module({+ controllers: [ToolsController],+ providers: [ToolsService],+ exports: [ToolsService],+})+export class ToolsModule {}diff --git a/backend/apps/cloud/src/tools/tools.service.ts b/backend/apps/cloud/src/tools/tools.service.tsnew file mode 100644index 000000000..55dd07ba6--- /dev/null+++ b/backend/apps/cloud/src/tools/tools.service.ts@@ -0,0 +1,59 @@+import { Injectable } from '@nestjs/common'+import net from 'net'+import { IpLookupResponseDto } from './dto/ip-lookup.dto'+import { getExtendedGeoDetails } from '../common/utils'++const EU_COUNTRIES = new Set([+ 'AT',+ 'BE',+ 'BG',+ 'HR',+ 'CY',+ 'CZ',+ 'DK',+ 'EE',+ 'FI',+ 'FR',+ 'DE',+ 'GR',+ 'HU',+ 'IE',+ 'IT',+ 'LV',+ 'LT',+ 'LU',+ 'MT',+ 'NL',+ 'PL',+ 'PT',+ 'RO',+ 'SK',+ 'SI',+ 'ES',+ 'SE',+])++@Injectable()+export class ToolsService {+ lookupIP(ip: string): IpLookupResponseDto {+ const ipVersion = net.isIPv4(ip) ? 4 : net.isIPv6(ip) ? 6 : 4+ const geo = getExtendedGeoDetails(ip)++ return {+ ip,+ country: geo.country,+ countryName: geo.countryName,+ city: geo.city,+ region: geo.region,+ regionCode: geo.regionCode,+ continentCode: geo.continentCode,+ continentName: geo.continentName,+ postalCode: geo.postalCode,+ latitude: geo.latitude,+ longitude: geo.longitude,+ timezone: geo.timezone,+ isInEuropeanUnion: geo.country ? EU_COUNTRIES.has(geo.country) : false,+ ipVersion,+ }+ }+}diff --git a/web/app/api/api.server.ts b/web/app/api/api.server.tsindex 4fc3dec9e..7fd73cd05 100644--- a/web/app/api/api.server.ts+++ b/web/app/api/api.server.ts@@ -34,7 +34,7 @@ function getApiUrl(): string {return apiUrl.endsWith('/') ? apiUrl : `${apiUrl}/`}-function getClientIP(request: Request): string | null {+export function getClientIP(request: Request): string | null {const headers = request.headersconst cfIP = headers.get('cf-connecting-ip')@@ -2050,10 +2050,7 @@ export async function generateSSOAuthURLServer(})}-export type {- SSOHashSuccessResponse,- SSOHashResponse,-} from '~/lib/models/Auth'+export type { SSOHashSuccessResponse, SSOHashResponse } from '~/lib/models/Auth'import type { SSOHashSuccessResponse, SSOHashResponse } from '~/lib/models/Auth'@@ -2375,3 +2372,38 @@ export async function getRevenueDataServer(`log/revenue?${queryParams.toString()}`,)}++// ============================================================================+// MARK: Tools API+// ============================================================================++export interface IpLookupResponse {+ ip: string+ country: string | null+ countryName: string | null+ city: string | null+ region: string | null+ regionCode: string | null+ continentCode: string | null+ continentName: string | null+ postalCode: string | null+ latitude: number | null+ longitude: number | null+ timezone: string | null+ isInEuropeanUnion: boolean+ ipVersion: 4 | 6+}++export async function getIpLookupServer(+ request: Request,+ ip: string,+): Promise<ServerFetchResult<IpLookupResponse>> {+ const queryParams = new URLSearchParams()+ queryParams.append('ip', ip)++ return serverFetch<IpLookupResponse>(+ request,+ `tools/ip-lookup?${queryParams.toString()}`,+ { skipAuth: true },+ )+}diff --git a/web/app/components/Footer/index.tsx b/web/app/components/Footer/index.tsxindex 964973be6..3995445d4 100644--- a/web/app/components/Footer/index.tsx+++ b/web/app/components/Footer/index.tsx@@ -60,6 +60,7 @@ const productionNavigation = {{ key: 'utm', href: routesPath.utm_generator, internal: true },{ key: 'ctr', href: routesPath.ctr_calculator, internal: true },{ key: 'roi', href: routesPath.roi_calculator, internal: true },+ { name: 'IP Lookup', href: routesPath.ip_lookup, internal: true },],company: [{ key: 'open', href: routesPath.open, internal: true },@@ -120,6 +121,11 @@ const communityEditionNavigation = {href: `https://swetrix.com${routesPath.roi_calculator}`,internal: false,},+ {+ name: 'IP Lookup',+ href: `https://swetrix.com${routesPath.ip_lookup}`,+ internal: false,+ },],company: [{ key: 'cloudEdition', href: 'https://swetrix.com', internal: false },@@ -352,13 +358,16 @@ const Footer = ({ showDBIPMessage }: FooterProps) => {<li className='mb-4 text-sm font-bold text-white uppercase'>{t('footer.resources')}</li>- {_map(navigation.resources, ({ key, href, internal }) => (- <li key={key} className='mb-2'>- <FooterLink href={href} internal={internal}>- {t(`footer.${key}`)}- </FooterLink>- </li>- ))}+ {_map(+ navigation.resources,+ ({ key, name, href, internal }) => (+ <li key={key} className='mb-2'>+ <FooterLink href={href} internal={internal}>+ {name || t(`footer.${key}`)}+ </FooterLink>+ </li>+ ),+ )}</ul></li>diff --git a/web/app/pages/Project/View/ViewProject.helpers.tsx b/web/app/pages/Project/View/ViewProject.helpers.tsxindex db53e21e0..cc7503d1c 100644--- a/web/app/pages/Project/View/ViewProject.helpers.tsx+++ b/web/app/pages/Project/View/ViewProject.helpers.tsx@@ -878,23 +878,25 @@ const getSettings = (const firstIndex = firstItem?.index ?? 0const currentX = firstItem?.x as Date | string | undefinedconst currentDate = currentX- ? (currentX instanceof Date ? currentX : new Date(currentX))+ ? currentX instanceof Date+ ? currentX+ : new Date(currentX): nullconst compareDate = compareChart?.x?.[firstIndex]const xDataValue = currentDate- ? (timeFormat === TimeFormat['24-hour']- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(currentDate)- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(currentDate))+ ? timeFormat === TimeFormat['24-hour']+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(currentDate)+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(currentDate): ''const xDataValueCompare = compareDate- ? (timeFormat === TimeFormat['24-hour']- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(- dayjs(compareDate).toDate(),- )- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(- dayjs(compareDate).toDate(),- ))+ ? timeFormat === TimeFormat['24-hour']+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(+ dayjs(compareDate).toDate(),+ )+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(+ dayjs(compareDate).toDate(),+ ): ''// Filter out compare series items@@ -943,7 +945,9 @@ const getSettings = (],),)- : compareChart?.[typesOptionsToTypesCompare[el.id]]?.[el.index]+ : compareChart?.[typesOptionsToTypesCompare[el.id]]?.[+ el.index+ ]if (compareValue === undefined || compareValue === null) return ''return `<li class='flex justify-between items-center py-px leading-snug'>@@ -1979,23 +1983,25 @@ const getSettingsPerf = (const firstIndex = firstItem?.index ?? 0const currentX = firstItem?.x as Date | string | undefinedconst currentDate = currentX- ? (currentX instanceof Date ? currentX : new Date(currentX))+ ? currentX instanceof Date+ ? currentX+ : new Date(currentX): nullconst compareDate = compareChart?.x?.[firstIndex]const xDataValue = currentDate- ? (timeFormat === TimeFormat['24-hour']- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(currentDate)- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(currentDate))+ ? timeFormat === TimeFormat['24-hour']+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(currentDate)+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(currentDate): ''const xDataValueCompare = compareDate- ? (timeFormat === TimeFormat['24-hour']- ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(- dayjs(compareDate).toDate(),- )- : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(- dayjs(compareDate).toDate(),- ))+ ? timeFormat === TimeFormat['24-hour']+ ? d3.timeFormat(tbsFormatMapperTooltip24h[timeBucket])(+ dayjs(compareDate).toDate(),+ )+ : d3.timeFormat(tbsFormatMapperTooltip[timeBucket])(+ dayjs(compareDate).toDate(),+ ): ''// Filter out compare series itemsdiff --git a/web/app/pages/Project/View/ViewProject.tsx b/web/app/pages/Project/View/ViewProject.tsxindex d55a447a0..ffe6f344f 100644--- a/web/app/pages/Project/View/ViewProject.tsx+++ b/web/app/pages/Project/View/ViewProject.tsx@@ -372,16 +372,21 @@ const ViewProjectContent = () => {const urlCompareTo = searchParams.get('compareTo')// Initialize dateRangeCompare from URL params if available- const [dateRangeCompare, setDateRangeCompare] = useState<null | Date[]>(() => {- if (urlCompareFrom && urlCompareTo) {- const fromDate = new Date(urlCompareFrom)- const toDate = new Date(urlCompareTo)- if (!Number.isNaN(fromDate.getTime()) && !Number.isNaN(toDate.getTime())) {- return [fromDate, toDate]+ const [dateRangeCompare, setDateRangeCompare] = useState<null | Date[]>(+ () => {+ if (urlCompareFrom && urlCompareTo) {+ const fromDate = new Date(urlCompareFrom)+ const toDate = new Date(urlCompareTo)+ if (+ !Number.isNaN(fromDate.getTime()) &&+ !Number.isNaN(toDate.getTime())+ ) {+ return [fromDate, toDate]+ }}- }- return null- })+ return null+ },+ )const dateRange = useMemo<Date[] | null>(() => {if (period !== 'custom') {@@ -608,7 +613,10 @@ const ViewProjectContent = () => {if (activePeriodCompare === 'previous') {// Calculate previous period dates based on current period- const currentActivePeriod = _find(periodPairs, (p) => p.period === period)+ const currentActivePeriod = _find(+ periodPairs,+ (p) => p.period === period,+ )if (period === 'custom' && dateRange) {// For custom period, calculate the same duration before the start date@@ -669,7 +677,16 @@ const ViewProjectContent = () => {if (shouldUpdate) {setSearchParams(newSearchParams)}- }, [isActiveCompare, activePeriodCompare, dateRangeCompare, period, dateRange, periodPairs, searchParams, setSearchParams])+ }, [+ isActiveCompare,+ activePeriodCompare,+ dateRangeCompare,+ period,+ dateRange,+ periodPairs,+ searchParams,+ setSearchParams,+ ])// Persist isActiveCompare to localStorageuseEffect(() => {diff --git a/web/app/routes/tools._index.tsx b/web/app/routes/tools._index.tsxindex 9cd0a3ea0..57e2a9cd7 100644--- a/web/app/routes/tools._index.tsx+++ b/web/app/routes/tools._index.tsx@@ -19,6 +19,19 @@ export async function loader() {}const TOOLS = [+ {+ title: 'IP Lookup',+ description:+ 'Find detailed geolocation information about any IP address including country, city, coordinates, and timezone',+ href: '/tools/ip-lookup',+ color: 'from-cyan-500 to-blue-600',+ features: [+ 'IP Geolocation',+ 'Country & City',+ 'Timezone Detection',+ 'Interactive Map',+ ],+ },{title: 'ROI Calculator',description:diff --git a/web/app/routes/tools.ip-lookup.tsx b/web/app/routes/tools.ip-lookup.tsxnew file mode 100644index 000000000..5b4b72009--- /dev/null+++ b/web/app/routes/tools.ip-lookup.tsx@@ -0,0 +1,614 @@+import {+ ChevronDownIcon,+ MagnifyingGlassIcon,+} from '@heroicons/react/24/outline'+import { useState, useEffect } from 'react'+import { redirect, useFetcher, useLoaderData } from 'react-router'+import type { SitemapFunction } from 'remix-sitemap'+import { ClientOnly } from 'remix-utils/client-only'++import { getIpLookupServer, getClientIP } from '~/api/api.server'+import { DitchGoogle } from '~/components/marketing/DitchGoogle'+import { isSelfhosted } from '~/lib/constants'+import Button from '~/ui/Button'+import Flag from '~/ui/Flag'+import Input from '~/ui/Input'+import { Text } from '~/ui/Text'+import Spin from '~/ui/icons/Spin'++export const sitemap: SitemapFunction = () => ({+ priority: 0.8,+ exclude: isSelfhosted,+})++export async function loader({ request }: { request: Request }) {+ if (isSelfhosted) {+ return redirect('/login', 302)+ }++ const userIp = getClientIP(request) || ''++ if (!userIp) {+ return {+ userIp: '',+ initialData: null,+ }+ }++ const result = await getIpLookupServer(request, userIp)++ return {+ userIp,+ initialData: result.data,+ }+}++export async function action({ request }: { request: Request }) {+ const formData = await request.formData()+ const ip = formData.get('ip') as string | null++ const clientIp = getClientIP(request) || ''+ const result = await getIpLookupServer(request, ip || clientIp)++ return {+ data: result.data,+ error: result.error,+ }+}++interface LocationMapProps {+ latitude: number+ longitude: number+ city?: string | null+ country?: string | null+}++function LocationMap({ latitude, longitude, city, country }: LocationMapProps) {+ const [MapComponents, setMapComponents] = useState<{+ MapContainer: any+ TileLayer: any+ Marker: any+ Popup: any+ } | null>(null)++ useEffect(() => {+ import('react-leaflet').then((module) => {+ setMapComponents({+ MapContainer: module.MapContainer,+ TileLayer: module.TileLayer,+ Marker: module.Marker,+ Popup: module.Popup,+ })+ })++ import('leaflet').then((L) => {+ delete (L.Icon.Default.prototype as any)._getIconUrl+ L.Icon.Default.mergeOptions({+ iconRetinaUrl:+ 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon-2x.png',+ iconUrl:+ 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-icon.png',+ shadowUrl:+ 'https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/images/marker-shadow.png',+ })+ })+ }, [])++ if (!MapComponents) {+ return (+ <div className='flex h-96 items-center justify-center rounded-lg bg-gray-50 dark:bg-slate-800'>+ <Spin />+ </div>+ )+ }++ const { MapContainer, TileLayer, Marker, Popup } = MapComponents++ return (+ <>+ <link+ rel='stylesheet'+ href='https://cdnjs.cloudflare.com/ajax/libs/leaflet/1.9.4/leaflet.min.css'+ />+ <MapContainer+ center={[latitude, longitude]}+ zoom={10}+ scrollWheelZoom={true}+ style={{ height: '384px', width: '100%', borderRadius: '0.5rem' }}+ attributionControl={false}+ >+ <TileLayer+ attribution='© <a href="https://www.openstreetmap.org/copyright">OpenStreetMap</a> contributors'+ url='https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'+ />+ <Marker position={[latitude, longitude]}>+ <Popup>+ {city && country+ ? `${city}, ${country}`+ : city || country || 'Location'}+ </Popup>+ </Marker>+ </MapContainer>+ </>+ )+}++const FAQ_ITEMS = [+ {+ question: 'How accurate is IP geolocation?',+ answer:+ "IP geolocation is generally accurate at the country and region level (95%+ accuracy). City-level accuracy varies between 50-80% depending on the ISP and network infrastructure. The coordinates provided are approximate and typically point to the ISP's network center rather than your exact physical location.",+ },+ {+ question: 'Can I hide my IP address?',+ answer:+ 'Yes, you can hide your real IP address using a VPN (Virtual Private Network), proxy server, or the Tor browser. These tools route your traffic through different servers, masking your original IP address and location.',+ },+ {+ question: 'Why does my IP location seem wrong?',+ answer:+ "IP geolocation databases may show incorrect locations due to: VPN or proxy usage, outdated database information, mobile network routing, or ISP infrastructure locations. The location shown typically represents where your ISP's network infrastructure is located, not your exact physical address.",+ },+ {+ question: 'Is IP lookup free?',+ answer:+ 'Yes, our IP lookup tool is completely free to use. You can check your own IP address or look up any public IP address without any cost or registration required.',+ },+ {+ question: 'What is ASN?',+ answer:+ 'ASN (Autonomous System Number) is a unique identifier assigned to networks on the internet. It helps identify which organization owns and operates a particular block of IP addresses, such as an ISP, company, or university.',+ },+ {+ question: 'What is the difference between IPv4 and IPv6?',+ answer:+ 'IPv4 uses 32-bit addresses (e.g., 192.168.1.1) and supports about 4.3 billion addresses. IPv6 uses 128-bit addresses (e.g., 2001:0db8:85a3::8a2e:0370:7334) and provides virtually unlimited addresses. Both formats are supported by our IP lookup tool.',+ },+ {+ question: 'Can I use this tool for security purposes?',+ answer:+ 'Yes, IP lookup is commonly used for security purposes including identifying suspicious login attempts, tracking potential threats, verifying user locations for fraud prevention, and investigating security incidents.',+ },+ {+ question: "How can I track my website visitors' locations?",+ answer:+ 'Swetrix provides privacy-focused website analytics that includes visitor geolocation data. You can see where your visitors come from by country, region, and city while respecting their privacy and complying with GDPR regulations.',+ },+]++function DataRow({+ label,+ value,+ secondary,+}: {+ label: string+ value: string | null | undefined+ secondary?: string | null+}) {+ return (+ <div className='flex items-baseline justify-between border-b border-gray-100 py-3 last:border-0 dark:border-slate-700/50'>+ <dt>+ <Text size='sm' colour='muted'>+ {label}+ </Text>+ </dt>+ <dd className='text-right'>+ <Text weight='medium'>{value || '—'}</Text>+ {secondary && (+ <Text size='sm' colour='muted' className='ml-2'>+ {secondary}+ </Text>+ )}+ </dd>+ </div>+ )+}++export default function IpLookup() {+ const { userIp, initialData } = useLoaderData<typeof loader>()+ const fetcher = useFetcher<typeof action>()++ const [ipInput, setIpInput] = useState(userIp || '')+ const [inputError, setInputError] = useState<string | null>(null)++ const isLoading =+ fetcher.state === 'submitting' || fetcher.state === 'loading'+ const data = fetcher.data?.data || initialData+ const apiError = fetcher.data?.error++ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault()+ setInputError(null)++ if (!ipInput.trim()) {+ setInputError('Please enter an IP address')+ return+ }++ fetcher.submit({ ip: ipInput }, { method: 'post' })+ }++ const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {+ setIpInput(e.target.value)+ if (inputError) {+ setInputError(null)+ }+ }++ const displayError =+ inputError ||+ (typeof apiError === 'string'+ ? apiError+ : apiError+ ? 'Failed to lookup IP address'+ : null)++ const hasCoordinates =+ data?.latitude !== null &&+ data?.longitude !== null &&+ data?.latitude !== undefined &&+ data?.longitude !== undefined++ const formatLocation = () => {+ const parts = [data?.city, data?.region, data?.countryName].filter(Boolean)+ return parts.join(', ') || null+ }++ return (+ <div className='min-h-screen bg-gray-50 dark:bg-slate-900'>+ <main className='mx-auto max-w-7xl px-4 py-12 sm:px-6 lg:px-8'>+ <div className='mx-auto max-w-3xl'>+ <div className='text-center'>+ <Text+ as='h1'+ size='4xl'+ weight='bold'+ tracking='tight'+ className='sm:text-5xl'+ >+ IP Address Lookup+ </Text>+ <Text as='p' size='lg' colour='muted' className='mt-4'>+ Find your IP address and get detailed geolocation data for any+ public IP.+ </Text>+ </div>++ <div className='mt-10'>+ <form onSubmit={handleSubmit} className='flex items-start gap-3'>+ <Input+ type='text'+ placeholder='Enter IP address (e.g., 8.8.8.8)'+ value={ipInput}+ onChange={handleInputChange}+ error={displayError}+ className='flex-1'+ />+ <Button+ type='submit'+ primary+ regular+ disabled={isLoading}+ className='mt-px'+ >+ {isLoading ? (+ <Spin className='h-4 w-4' />+ ) : (+ <>+ <MagnifyingGlassIcon className='mr-1.5 h-4 w-4' />+ Lookup+ </>+ )}+ </Button>+ </form>+ </div>++ {data && (+ <div className='mt-6 space-y-8'>+ <section className='rounded-xl bg-white p-6 ring-1 ring-gray-200 dark:bg-slate-800 dark:ring-slate-700'>+ <div className='mb-6 flex items-center gap-4'>+ {data.country && (+ <Flag+ className='rounded-xs'+ country={data.country}+ size={40}+ alt={data.countryName || data.country}+ />+ )}+ <div>+ <Text+ as='p'+ size='2xl'+ weight='semibold'+ className='font-mono'+ >+ {data.ip}+ </Text>+ {formatLocation() && (+ <Text as='p' colour='muted' className='mt-0.5'>+ {formatLocation()}+ </Text>+ )}+ </div>+ </div>++ <dl>+ <DataRow+ label='IP Version'+ value={data.ipVersion ? `IPv${data.ipVersion}` : null}+ />+ <DataRow+ label='Country'+ value={data.countryName}+ secondary={data.country}+ />+ <DataRow+ label='Region'+ value={data.region}+ secondary={data.regionCode}+ />+ <DataRow label='City' value={data.city} />+ <DataRow label='Postal Code' value={data.postalCode} />+ <DataRow+ label='Continent'+ value={data.continentName}+ secondary={data.continentCode}+ />+ <DataRow+ label='Coordinates'+ value={+ hasCoordinates+ ? `${data.latitude?.toFixed(4)}, ${data.longitude?.toFixed(4)}`+ : null+ }+ />+ <DataRow label='Timezone' value={data.timezone} />+ {data.isInEuropeanUnion && (+ <DataRow label='EU Member' value='Yes' />+ )}+ </dl>+ </section>++ {hasCoordinates && (+ <section className='overflow-hidden rounded-xl ring-1 ring-gray-200 dark:ring-slate-700'>+ <ClientOnly+ fallback={+ <div className='flex h-96 items-center justify-center bg-gray-50 dark:bg-slate-800'>+ <Spin />+ </div>+ }+ >+ {() => (+ <LocationMap+ latitude={data.latitude!}+ longitude={data.longitude!}+ city={data.city}+ country={data.countryName}+ />+ )}+ </ClientOnly>+ </section>+ )}+ </div>+ )}++ <section className='mt-20 border-t border-gray-200 pt-16 dark:border-slate-700'>+ <Text as='h2' size='3xl' weight='bold' tracking='tight'>+ Free IP Address Lookup Tool+ </Text>+ <Text+ as='p'+ size='lg'+ colour='muted'+ className='mt-4 leading-relaxed'+ >+ Wondering "what is my IP address?" Our free IP lookup tool+ instantly shows your public IP address and provides detailed+ geolocation data including country, city, region, coordinates, and+ timezone. You can also look up any IPv4 or IPv6 address to find+ its location and network information.+ </Text>++ <div className='mt-12 grid gap-x-12 gap-y-10 md:grid-cols-2'>+ <div>+ <Text as='h3' size='xl' weight='semibold'>+ What is an IP Address?+ </Text>+ <Text as='p' colour='muted' className='mt-3'>+ An IP (Internet Protocol) address is a unique numerical+ identifier assigned to every device connected to the internet.+ It works like a mailing address, allowing data to be routed to+ and from your device. There are two formats:{' '}+ <Text as='span' weight='semibold' colour='inherit'>+ IPv4+ </Text>{' '}+ (e.g., 192.168.1.1) with about 4.3 billion possible addresses,+ and{' '}+ <Text as='span' weight='semibold' colour='inherit'>+ IPv6+ </Text>{' '}+ (e.g., 2001:0db8:85a3::8a2e:0370:7334) which provides+ virtually unlimited addresses.+ </Text>+ </div>++ <div>+ <Text as='h3' size='xl' weight='semibold'>+ How IP Geolocation Works+ </Text>+ <Text as='p' colour='muted' className='mt-3'>+ IP geolocation determines the approximate physical location of+ an IP address by analyzing routing information and regional IP+ allocations. Our tool uses the DB-IP database to provide+ accurate country-level data (95%+ accuracy) and city-level+ estimates (50-80% accuracy). The location typically represents+ your ISP's network center, not your exact address.+ </Text>+ </div>++ <div>+ <Text as='h3' size='xl' weight='semibold'>+ Common Use Cases+ </Text>+ <ul className='mt-3 space-y-2'>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ Security monitoring+ </Text>{' '}+ - Identify suspicious login attempts from unusual+ locations+ </Text>+ </li>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ Fraud prevention+ </Text>{' '}+ - Verify user locations to detect potentially fraudulent+ activity+ </Text>+ </li>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ Content localization+ </Text>{' '}+ - Serve region-specific content based on visitor location+ </Text>+ </li>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ Compliance+ </Text>{' '}+ - Enforce geographic restrictions for regulatory+ requirements+ </Text>+ </li>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ Analytics+ </Text>{' '}+ - Understand where your website visitors are located+ </Text>+ </li>+ </ul>+ </div>++ <div>+ <Text as='h3' size='xl' weight='semibold'>+ What Data is Included+ </Text>+ <ul className='mt-3 space-y-2'>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ Geographic location+ </Text>{' '}+ - Country, region/state, city, and postal code+ </Text>+ </li>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ Coordinates+ </Text>{' '}+ - Latitude and longitude for mapping+ </Text>+ </li>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ Timezone+ </Text>{' '}+ - The timezone associated with the IP location+ </Text>+ </li>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ IP version+ </Text>{' '}+ - Whether the address is IPv4 or IPv6+ </Text>+ </li>+ <li>+ <Text colour='muted'>+ <Text as='span' weight='semibold' colour='inherit'>+ EU status+ </Text>{' '}+ - Whether the IP is located in the European Union+ </Text>+ </li>+ </ul>+ </div>+ </div>++ <div className='mt-12'>+ <Text as='h3' size='xl' weight='semibold'>+ How to Use This IP Checker+ </Text>+ <Text as='p' colour='muted' className='mt-3'>+ Your IP address is automatically detected when you visit this+ page. To look up a different IP, simply enter any public IPv4 or+ IPv6 address in the search box above and click "Lookup." The+ results will show the geographic location on an interactive map+ along with detailed network information. This tool is completely+ free - no registration or limits.+ </Text>+ </div>+ </section>++ <section className='mt-16'>+ <Text as='h2' size='2xl' weight='bold' className='mb-6'>+ FAQ+ </Text>++ <div className='space-y-3'>+ {FAQ_ITEMS.map((item, index) => (+ <details+ key={index}+ className='group rounded-lg border border-gray-200 bg-white dark:border-slate-700 dark:bg-slate-800'+ >+ <summary className='flex cursor-pointer items-center justify-between px-5 py-4 text-left'>+ <Text weight='medium'>{item.question}</Text>+ <ChevronDownIcon className='h-5 w-5 shrink-0 text-gray-400 transition-transform group-open:rotate-180' />+ </summary>+ <div className='border-t border-gray-200 px-5 py-4 dark:border-slate-700'>+ <Text as='p' colour='muted'>+ {item.answer}+ </Text>+ </div>+ </details>+ ))}+ </div>+ </section>++ <script+ type='application/ld+json'+ dangerouslySetInnerHTML={{+ __html: JSON.stringify({+ '@context': 'https://schema.org',+ '@type': 'FAQPage',+ mainEntity: FAQ_ITEMS.map((item) => ({+ '@type': 'Question',+ name: item.question,+ acceptedAnswer: {+ '@type': 'Answer',+ text: item.answer,+ },+ })),+ })+ .replace(/</g, '\\u003c')+ .replace(/\u2028|\u2029/g, ''),+ }}+ />++ <DitchGoogle />+ </div>+ </main>+ </div>+ )+}diff --git a/web/app/utils/routes.ts b/web/app/utils/routes.tsindex c161ad34f..abc2cad94 100644--- a/web/app/utils/routes.ts+++ b/web/app/utils/routes.ts@@ -42,6 +42,7 @@ const routes = Object.freeze({utm_generator: '/tools/utm-generator',roi_calculator: '/tools/roi-calculator',ctr_calculator: '/tools/ctr-calculator',+ ip_lookup: '/tools/ip-lookup',// Marketing pagesgaAlternative: '/google-analytics-alternative',