Android examples for Network:Network Operation
get Local IP Address from NetworkInterface
//package com.java2s; import java.net.Inet4Address; import java.net.InetAddress; import java.net.NetworkInterface; import java.net.SocketException; import java.util.Enumeration; import android.util.Log; public class Main { private final static String P2P_INT = "p2p0"; public static String getLocalIPAddress() { try {//from ww w. j a v a2 s . co m for (Enumeration<NetworkInterface> en = NetworkInterface .getNetworkInterfaces(); en.hasMoreElements();) { NetworkInterface intf = en.nextElement(); for (Enumeration<InetAddress> enumIpAddr = intf .getInetAddresses(); enumIpAddr.hasMoreElements();) { InetAddress inetAddress = enumIpAddr.nextElement(); String iface = intf.getName(); if (iface.matches(".*" + P2P_INT + ".*")) { if (inetAddress instanceof Inet4Address) { return getDottedDecimalIP(inetAddress .getAddress()); } } } } } catch (SocketException ex) { Log.e("AndroidNetworkAddressFactory", "getLocalIPAddress()", ex); } catch (NullPointerException ex) { Log.e("AndroidNetworkAddressFactory", "getLocalIPAddress()", ex); } return null; } private static String getDottedDecimalIP(byte[] ipAddr) { String ipAddrStr = ""; for (int i = 0; i < ipAddr.length; i++) { if (i > 0) { ipAddrStr += "."; } ipAddrStr += ipAddr[i] & 0xFF; } return ipAddrStr; } }