写一个java程序输入参数为一个字符串类型的IP地址输出IP所在地区
由于IP地址的归属地信息需要查询数据库,因此需要使用第三方库进行查询。这里我们使用MaxMind的GeoIP2 Java API。
首先需要下载并导入GeoIP2 Java API的jar包,然后编写以下程序:
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import java.io.File;
import java.net.InetAddress;
import java.util.Scanner;
public class IpLocation {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入IP地址:");
String ip = scanner.nextLine();
try {
// 读取数据库文件
File database = new File("GeoLite2-City.mmdb");
DatabaseReader reader = new DatabaseReader.Builder(database).build();
// 解析IP地址
InetAddress ipAddress = InetAddress.getByName(ip);
// 查询IP所在地区
CityResponse response = reader.city(ipAddress);
City city = response.getCity();
String country = response.getCountry().getName();
String province = city.getProvince().getName();
String cityname = city.getName();
// 输出结果
System.out.println("IP地址:" + ip);
System.out.println("所在国家:" + country);
System.out.println("所在省份:" + province);
System.out.println("所在城市:" + cityname);
} catch (Exception e) {
System.out.println("查询失败:" + e.getMessage());
}
}
}
运行程序,输入一个IP地址,即可查询该IP地址所在的国家、省份和城市信息。需要注意的是,需要将GeoLite2-City.mmdb文件放在程序的同级目录下,并且该文件在程序运行时必须可读
原文地址: https://www.cveoy.top/t/topic/faRD 著作权归作者所有。请勿转载和采集!