get Local Inet Address - Android Network

Android examples for Network:IP Address

Description

get Local Inet Address

Demo Code


//package com.java2s;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

public class Main {
    public static InetAddress getLocalInetAddress(Context context) {
        int address = getLocalIpAddress(context);
        if (address == 0) {
            return null;
        }//from   w w  w . jav a  2s.c  om
        try {
            return transform(address);
        } catch (UnknownHostException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static int getLocalIpAddress(Context context) {
        WifiManager wifiManager = (WifiManager) context
                .getSystemService(Context.WIFI_SERVICE);
        WifiInfo wifiInfo = wifiManager.getConnectionInfo();
        return wifiInfo.getIpAddress();
    }

    public static InetAddress transform(int ip) throws UnknownHostException {
        byte[] arrayOfByte = new byte[4];
        arrayOfByte[3] = ((byte) (0xFF & (ip >> 24)));
        arrayOfByte[2] = ((byte) (0xFF & (ip >> 16)));
        arrayOfByte[1] = ((byte) (0xFF & (ip >> 8)));
        arrayOfByte[0] = ((byte) (ip & 0xFF));
        InetAddress localInetAddress = InetAddress
                .getByAddress(arrayOfByte);
        return localInetAddress;
    }
}

Related Tutorials