我已经编写了一段代码来获取与每个接口关联的所有私有ip。我将所有私有ip存储在数组列表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 ip,并想调用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 "ip .get(" internali ")">
,可以找到所需的公共ipprivate 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);
}