Android examples for java.net:IP Address
get Ip Address
import java.net.InterfaceAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiInfo; import android.net.wifi.WifiManager; public class Main { public static String getIpAddress(Context context) { String type = getNetWorkType(context); if (type.equals("WIFI")) { WifiManager wm = (WifiManager) context.getSystemService(Context.WIFI_SERVICE); WifiInfo wi = wm.getConnectionInfo(); int int_ip = wi.getIpAddress(); int[] ip = new int[4]; for (int i = 0; i < 4; i++) { ip[i] = ((1 << 8) - 1) & (int_ip >> i * 8); }/* w w w . j av a 2 s.c om*/ return ip[0] + "." + ip[1] + "." + ip[2] + '.' + ip[3]; } if (type.equals("ETHERNET") || type.equals("MOBILE")) { try { Enumeration<NetworkInterface> eni = NetworkInterface.getNetworkInterfaces(); while (eni.hasMoreElements()) { NetworkInterface ni = eni.nextElement(); if (!ni.getDisplayName().equals("eth0")) continue; for (InterfaceAddress ifa : ni.getInterfaceAddresses()) { String ip = ifa.getAddress().toString(); if (ip.contains(".")) { return ip.substring(1, ip.length()); } } } } catch (SocketException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return "0.0.0.0"; } public static String getNetWorkType(Context context) { ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); return ni.getTypeName(); } }