一、在window下獲取本機ip地址java
InetAddress inet = InetAddress.getLocalHost(); System.out.println("本機的ip=" + inet.getHostAddress());
該方法在linux下獲取到的ip爲127.0.0.1,緣由是你linux服務器上hosts配置了 127.0.0.1 localhostlinux
能夠修改hosts下將127.0.0.1改爲你的本機真實ip地址
服務器
二、linux下代碼獲取本機ip地址oop
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 ""; }