通过命令获取IP
本文获取的是 项目所在系统的IP(本地IP)
本地IP分为两个:局域网IP 和 公网IP 。下面是具体的代码实现(Windows 和 Linux 均适用)。。
测试代码
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
/**
* @author yy
* @date 2022/2/16
*/
public class IPTest {
public static void main(String[] args) throws Exception {
System.out.println(IPTest.getInterIP1());
System.out.println(IPTest.getInterIP2());
System.out.println(IPTest.getInterIP3());
}
public static String getInterIP1() throws Exception {
return InetAddress.getLocalHost().getHostAddress();
}
public static String getInterIP2() throws SocketException {
String localip = null;// 本地IP,如果没有配置外网IP则返回它
String netip = null;// 外网IP
Enumeration<NetworkInterface> netInterfaces;
netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
boolean finded = false;// 是否找到外网IP
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
localip = ip.getHostAddress();
}
}
}
if (netip != null && !"".equals(netip)) {
return netip;
} else {
return localip;
}
}
public static String getInterIP3() throws IOException, InterruptedException {
//通过命令获取外网ip
String command = "curl -L ip.tool.lu";
String[] commandSplit = command.split(" ");
List<String> lcommand = new ArrayList<String>();
for (int i = 0; i < commandSplit.length; i++) {
lcommand.add(commandSplit[i]);
}
ProcessBuilder processBuilder = new ProcessBuilder(lcommand);
processBuilder.redirectErrorStream(true);
Process p = processBuilder.start();
InputStream is = p.getInputStream();
BufferedReader bs = new BufferedReader(new InputStreamReader(is));
p.waitFor();
if (p.exitValue() != 0) {
//说明命令执行失败
//可以进入到错误处理步骤中
}
String line = null;
while ((line = bs.readLine()) != null) {
if(line.startsWith("当前IP:")){
return line.replace("当前IP:","").trim();
}
}
return "";
}
}
参考地址:https://blog.csdn.net/qq_37171353/article/details/105480375
参考地址:https://www.cnblogs.com/bencakes/p/6139477.html
直接使用:curl icanhazip.com