Linux下取真实ip

private static String getLocalIP() throws SocketException {
  Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
  InetAddress rtip = null;
  while (netInterfaces.hasMoreElements()) {
   NetworkInterface ni = netInterfaces.nextElement();
   logger.info("interface name:" + ni.getName());
   Enumeration<InetAddress> addresses = ni.getInetAddresses();
   while(addresses.hasMoreElements()){
    InetAddress ip = addresses.nextElement();
    if (ip!=null && !ip.isLoopbackAddress() && ip instanceof Inet4Address) {
     logger.info("本机的ip=" + ip.getHostAddress());
     rtip = ip;
     break;
    }
   }
   if(rtip!=null){
    break;
   }
  }
  if(rtip!=null){
   return rtip.getHostAddress();
  }else{
   return null;
  }
 }

你可能感兴趣的:(linux)