Java tutorial
//package com.java2s; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.util.Log; import java.net.InetAddress; import java.net.NetworkInterface; import java.util.Enumeration; public class Main { /** * The constant TAG. */ public static final String TAG = "DeviceUtil"; private static ConnectivityManager connectivityManager; private static Context mContext; /** * Gets ip. * * @return the ip */ public static String getIp() { String res = null; if (isWifiConnected()) { res = getIpUnderWifi(); } else { res = getIpWithoutWifi(); } return res; } public static boolean isWifiConnected() { NetworkInfo ni = connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); return ni.isConnected(); } private static String getIpUnderWifi() { WifiManager wifiManager = (WifiManager) mContext.getSystemService(Context.WIFI_SERVICE); int ipAddress = wifiManager.getConnectionInfo().getIpAddress(); Log.w(TAG, "getIp isWifiConnected ipaddress=" + ipAddress); return String.format("%d.%d.%d.%d", ipAddress & 0xff, ipAddress >> 8 & 0xff, ipAddress >> 16 & 0xff, ipAddress >> 24 & 0xff); } public static String getIpWithoutWifi() { try { for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en .hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumeration = intf.getInetAddresses(); en.hasMoreElements();) { InetAddress inetAddress = enumeration.nextElement(); if (inetAddress.isLoopbackAddress()) { return inetAddress.getHostAddress().toString(); } } } } catch (Exception e) { Log.w(TAG, "getIpWithoutWifi error:" + e.getMessage()); } return null; } }