Java程序:将IP地址转换为地理位置
该程序需要依赖第三方库GeoLite2-City.mmdb,需要先下载该库并引入到项目中。
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import java.io.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
public class IPtoLocation {
public static void main(String[] args) throws IOException, GeoIp2Exception {
// 输入文件路径和输出文件路径
String inputFilePath = 'input.txt';
String outputFilePath = 'output.txt';
// 读取IP地址
BufferedReader reader = new BufferedReader(new FileReader(inputFilePath));
String ip;
StringBuilder result = new StringBuilder();
while ((ip = reader.readLine()) != null) {
try {
// 获取IP所在地区
String location = getLocation(ip);
// 拼接IP和所在地区
result.append(ip).append(' ').append(location).append(System.lineSeparator());
} catch (UnknownHostException e) {
// IP地址无效,不做处理
}
}
reader.close();
// 写入结果到输出文件
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFilePath));
writer.write(result.toString());
writer.close();
}
private static String getLocation(String ip) throws IOException, GeoIp2Exception {
// 读取IP库
File database = new File('GeoLite2-City.mmdb');
DatabaseReader reader = new DatabaseReader.Builder(database).build();
// 查询IP所在地区
InetAddress ipAddress = InetAddress.getByName(ip);
CityResponse response = reader.city(ipAddress);
// 拼接所在地区信息
String country = response.getCountry().getName();
String subdivision = response.getMostSpecificSubdivision().getName();
String city = response.getCity().getName();
return country + ' ' + subdivision + ' ' + city;
}
}
该程序通过读取输入文件中的IP地址,使用GeoLite2-City.mmdb库查询每个IP地址的地理位置信息,并将结果写入输出文件。
使用说明:
- 下载GeoLite2-City.mmdb库文件并将其放置在程序目录下。
- 将输入IP地址列表写入名为'input.txt'的文件中,每个IP地址占一行。
- 运行程序,程序会自动生成名为'output.txt'的文件,其中包含每个IP地址及其对应的地理位置信息。
注意:
- 该程序需要在项目中引入GeoLite2-City.mmdb库的依赖。
- GeoLite2-City.mmdb库是一个付费库,需要购买授权才能使用。
- 该程序仅提供示例,实际使用中需要根据具体情况进行调整。
原文地址: https://www.cveoy.top/t/topic/n3Da 著作权归作者所有。请勿转载和采集!