public static InetAddress findInetAddress() throws SocketException, UnknownHostException {
  final Enumeration<NetworkInterface> enum1=NetworkInterface.getNetworkInterfaces();
  if (enum1 == null) {
    final InetAddress ip1=InetAddress.getLocalHost();
    return ip1;
  }
  final List<InetAddress> allButLoopback=new ArrayList<>();
  while (enum1.hasMoreElements()) {
    final NetworkInterface netface=enum1.nextElement();
    final Enumeration<InetAddress> enum2=netface.getInetAddresses();
    while (enum2.hasMoreElements()) {
      final InetAddress ip2=enum2.nextElement();
      if (!ip2.isLoopbackAddress()) {
        allButLoopback.add(ip2);
      }
    }
  }
  for (  final InetAddress address : allButLoopback) {
    if (address.getAddress().length == 4 && !isPrivateNetworkAddress(address)) {
      return address;
    }
  }
  for (  final InetAddress address : allButLoopback) {
    if (!isPrivateNetworkAddress(address)) {
      return address;
    }
  }
  for (  final InetAddress address : allButLoopback) {
    if (!address.isLinkLocalAddress()) {
      return address;
    }
  }
  return InetAddress.getLocalHost();
}

public static InetAddress findInetAddress ( ) throws SocketException , UnknownHostException { final Enumeration < NetworkInterface > enum1 = NetworkInterface . getNetworkInterfaces ( ) ; if ( enum1 == null ) { final InetAddress ip1 = InetAddress . getLocalHost ( ) ; return ip1 ; } final List < InetAddress > allButLoopback = new ArrayList < > ( ) ; while ( enum1 . hasMoreElements ( ) ) { final NetworkInterface netface = enum1 . nextElement ( ) ; final Enumeration < InetAddress > enum2 = netface . getInetAddresses ( ) ; while ( enum2 . hasMoreElements ( ) ) { final InetAddress ip2 = enum2 . nextElement ( ) ; if ( ! ip2 . isLoopbackAddress ( ) ) { allButLoopback . add ( ip2 ) ; } } } for ( final InetAddress address : allButLoopback ) { if ( address . getAddress ( ) . length == 4 && ! isPrivateNetworkAddress ( address ) ) { return address ; } } for ( final InetAddress address : allButLoopback ) { if ( ! isPrivateNetworkAddress ( address ) ) { return address ; } } for ( final InetAddress address : allButLoopback ) { if ( ! address . isLinkLocalAddress ( ) ) { return address ; } } return InetAddress . getLocalHost ( ) ; }
we iterate through an enumeration of network interfaces on the machine and picks the first ip that is not a loopback and not a link local and not private . in the case of irix computers connected on a lan through a central gateway running java off a telnet session will result in a null network interface ( patched below ) .
