该程序需要依赖第三方库,使用了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;
}
写一个java程序输入参数为一个文件文件内容每一行为一个字符串类型的IP地址输出一个文件内容为IP加IP所在地区

原文地址: https://www.cveoy.top/t/topic/faRO 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录