package mobi.monaca.framework.util; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Collections; import java.util.List; import org.apache.http.conn.util.InetAddressUtils; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class NetworkUtils { /** * Get IP address from first non-localhost interface * * @param ipv4 * true=return ipv4, false=return ipv6 * @return address or empty string */ public static String getIPAddress(boolean useIPv4) { try { List<NetworkInterface> interfaces = Collections .list(NetworkInterface.getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf .getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String sAddr = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(sAddr); if (useIPv4) { if (isIPv4) return sAddr; } else { if (!isIPv4) { int delim = sAddr.indexOf('%'); // drop ip6 port // suffix return delim < 0 ? sAddr : sAddr.substring(0, delim); } } } } } } catch (Exception ex) { } // for now eat exceptions return ""; } public static JSONObject getIPAddresses() throws SocketException, JSONException { JSONObject networkJson= new JSONObject(); List<NetworkInterface> interfaces = Collections.list(NetworkInterface .getNetworkInterfaces()); for (NetworkInterface intf : interfaces) { List<InetAddress> addrs = Collections.list(intf.getInetAddresses()); for (InetAddress addr : addrs) { if (!addr.isLoopbackAddress()) { String ipAddress = addr.getHostAddress().toUpperCase(); boolean isIPv4 = InetAddressUtils.isIPv4Address(ipAddress); if (isIPv4) { String interfacename = intf.getName(); networkJson.put(interfacename, ipAddress); } } } } return networkJson; } }