1、在window下获取本机ip地址
InetAddress inet = InetAddress.getLocalHost();
System.out.println("本机的ip=" + inet.getHostAddress());
该方法在linux下获取到的ip为127.0.0.1,原因是你linux服务器上hosts配置了 127.0.0.1 localhost
可以修改hosts下将127.0.0.1改成你的本机真实ip地址
2、linux下代码获取本机ip地址
public static String getLocalHostIP() {
try {
for (Enumeration<NetworkInterface> nis = NetworkInterface
.getNetworkInterfaces(); nis.hasMoreElements();) {
NetworkInterface ni = nis.nextElement();
if (ni.isLoopback() || !ni.isUp())
continue;
for (Enumeration<InetAddress> ias = ni.getInetAddresses(); ias.hasMoreElements();) {
InetAddress ia = ias.nextElement();
if (ia instanceof Inet6Address) continue;
return ia.getHostAddress();
}
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}