java 记录ip和地址
要记录IP地址和地址,可以使用Java的InetAddress类和URL类。
首先,要记录IP地址,可以使用InetAddress类的getLocalHost()方法来获取本地主机的IP地址。例如:
InetAddress localHost = InetAddress.getLocalHost();
String ipAddress = localHost.getHostAddress();
System.out.println("IP地址:" + ipAddress);
要记录地址,可以使用URL类来解析IP地址对应的地址。例如:
URL url = new URL("http://ip-api.com/json/" + ipAddress);
URLConnection connection = url.openConnection();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
StringBuilder response = new StringBuilder();
while ((line = reader.readLine()) != null) {
response.append(line);
}
reader.close();
JSONObject jsonObject = new JSONObject(response.toString());
String country = jsonObject.getString("country");
String city = jsonObject.getString("city");
System.out.println("地址:" + country + ", " + city);
这里使用了一个免费的IP地址查询API(http://ip-api.com/json/),可以根据IP地址获取该地址的详细信息。使用URL类打开连接,并使用BufferedReader读取返回的数据。然后,将返回的JSON字符串解析为JSONObject,从中获取国家和城市信息。
需要注意的是,使用第三方API可能需要遵守其使用规则和限制。上述示例仅作为参考,请根据实际需要进行修改和调整
原文地址: https://www.cveoy.top/t/topic/h0Kd 著作权归作者所有。请勿转载和采集!