import { publicIpv4 } from "public-ip";
interface IpApiResponse {
status: string;
message?: string;
country: string;
countryCode: string;
regionName: string;
region: string;
city: string;
zip: string;
lat: number;
lon: number;
timezone: string;
isp: string;
org: string;
as: string;
}
export async function getLocationInfo(ip?: string) {
try {
// 如果没有提供IP,获取当前公网IP
const targetIp = ip || await publicIpv4();
// 使用免费的 IP 地理位置 API
const response = await fetch(`http://ip-api.com/json/${targetIp}?lang=zh-CN`);
if (!response.ok) {
throw new Error(`API请求失败: ${response.status}`);
}
const data = await response.json() as IpApiResponse;
if (data.status === "fail") {
throw new Error(data.message || "无法获取位置信息");
}
return {
ip: targetIp,
country: data.country,
countryCode: data.countryCode,
region: data.regionName,
regionCode: data.region,
city: data.city,
zip: data.zip,
latitude: data.lat,
longitude: data.lon,
timezone: data.timezone,
isp: data.isp,
org: data.org,
as: data.as,
};
} catch (error) {
if (error instanceof Error) {
throw new Error(`获取位置信息失败: ${error.message}`);
}
throw error;
}
}