Android IP Address Get getLocalHostAddress()

Here you can find the source of getLocalHostAddress()

Description

get Local Host Address

License

Open Source License

Declaration

@SuppressLint("DefaultLocale")
    public static String getLocalHostAddress() 

Method Source Code

//package com.java2s;
import java.net.InetAddress;
import java.net.NetworkInterface;

import java.util.Collections;
import java.util.List;
import org.apache.http.conn.util.InetAddressUtils;
import android.annotation.SuppressLint;

public class Main {
    @SuppressLint("DefaultLocale")
    public static String getLocalHostAddress() {
        boolean useIPv4 = true;

        try {/*ww  w.  j a v a2  s  .c o m*/
            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 "";
    }
}

Related

  1. getByteAddress(BluetoothDevice device)
  2. getInetIpAddress()
  3. getLocalIpAddress()
  4. getIPAddress(boolean useIPv4)
  5. getHostAddress(int address)
  6. getIPAddress(boolean useIPv4)
  7. getTargetInetaddress(String target)
  8. getDevicesMac(Context context)
  9. getDevicesIP(Context context)