[英]Get public ip associated with the private ip in Java using http request to ifconfig.co
我编写了一个代码来获取与每个接口关联的所有私有 ip。 我将所有私有 ips 存储在 ArrayList ips
中。
List<String> ips = new ArrayList<>();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
ips.add(enumIpAddr.nextElement().toString().replace("/", ""));
}
}
现在我想遍历 List ips 并想调用 http 请求来获取公共 ip。 下面是 linux curl 命令,它将返回与私有 ip 10.74.4.11 关联的公共 ip。
curl -i --interface 10.74.4.11 "ifconfig.co"
我只想将此 linux 命令转换为我可以在我的程序中使用的 java http 请求。
此方法使用 Java Runtime API 执行命令,然后将找到的公共 ip 作为值添加到 hashmap 到 internalIp 键。 所以最后你可以通过搜索 hashmap "ips.get("internalIp")" 找到所需的公共 ip
private static void getIps() throws IOException {
Map<String, String> ips = new HashMap<>();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
ips.put(enumIpAddr.nextElement().toString().replace("/", ""), "");
}
}
for (String ip: ips.keySet())
{
String command="curl --interface "+ ip+" ifconfig.co";
System.out.println("Excecuting: "+command);
Process process = Runtime.getRuntime().exec(command);
try {
process.waitFor();
final int exitValue = process.waitFor();
if (exitValue == 0) {
System.out.println("Successfully executed the command: " + command);
List<String> result = new BufferedReader(new InputStreamReader(process.getInputStream()))
.lines().collect(Collectors.toList());
ips.put(ip, result.get(result.size()-1));//the public IP will be the last item in the result stream
}
else {
System.out.println("Failed to execute the following command: " + command + " due to the following error(s):");
try (final BufferedReader b = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
String line;
if ((line = b.readLine()) != null)
System.out.println(line);
} catch (final IOException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(ips);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.