我现在在windows平台使用idea编写javaweb后端代码,并打算后期将项目移植到linux系统的阿里云服务器中。但是我在试图获取本机ip时遇到了麻烦。
我用来获取ip地址的方法如下:
public static String getIpAddress() {
try {
Enumeration<NetworkInterface> allNetInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
while (allNetInterfaces.hasMoreElements()) {
NetworkInterface netInterface = (NetworkInterface) allNetInterfaces.nextElement();
if (netInterface.isLoopback() || netInterface.isVirtual() || !netInterface.isUp()) {
continue;
} else {
Enumeration<InetAddress> addresses = netInterface.getInetAddresses();
while (addresses.hasMoreElements()) {
ip = addresses.nextElement();
if (ip != null && ip instanceof Inet4Address) {
return ip.getHostAddress();
}
}
}
}
} catch (Exception e) {
System.err.println("IP地址获取失败" + e.toString());
}
return "";
}
但是这串代码返回的不是我想要的ip地址。这是我的电脑的几个ip地址:
框选的是我想要的ip地址。因为我在使用android前端做测试,手机和电脑都是连同一个wifi,上面方法返回的ip地址我的手机无法访问,请问有什么办法可以解决吗?