get Local Ip Address - Android Phone

Android examples for Phone:Network

Description

get Local Ip Address

Demo Code


//package com.java2s;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

import java.util.Enumeration;

public class Main {
    public static String getLocalIpAddress() {
        try {//w  ww.j  a  va2  s .c o m
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements();) {
                NetworkInterface ni = (NetworkInterface) en.nextElement();

                for (Enumeration<InetAddress> enumIpAddr = ni
                        .getInetAddresses(); enumIpAddr.hasMoreElements();) {
                    InetAddress inetAddress = (InetAddress) enumIpAddr
                            .nextElement();

                    if (!inetAddress.isLoopbackAddress()
                            && !inetAddress.isLinkLocalAddress()
                            && inetAddress.isSiteLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException se) {
            se.printStackTrace();
        }

        return null;
    }
}

Related Tutorials