现在的位置: 首页 > 综合 > 正文

获取手机ip地址工具类

2013年10月10日 ⁄ 综合 ⁄ 共 1293字 ⁄ 字号 评论关闭

package com.innofidei.location;

import java.net.InetAddress;
import java.net.UnknownHostException;

import android.content.Context;
import android.net.wifi.WifiManager;

public class AdressUtil {
	public String getIp(Context myContext) {
		InetAddress address = getWifiIp(myContext);
		if (address != null) {
			return address.getHostAddress();
		}
		return null;
	}

	private InetAddress getWifiIp(Context myContext) {
		if (myContext == null) {
			throw new NullPointerException("Global context is null");
		}
		WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
		if (isWifiEnabled(myContext)) {
			int ipAsInt = wifiMgr.getConnectionInfo().getIpAddress();
			if (ipAsInt == 0) {
				return null;
			} else {
				return intToInet(ipAsInt);
			}
		} else {
			return null;
		}
	}

	private boolean isWifiEnabled(Context myContext) {
		if (myContext == null) {
			throw new NullPointerException("Global context is null");
		}
		WifiManager wifiMgr = (WifiManager) myContext.getSystemService(Context.WIFI_SERVICE);
		if (wifiMgr.getWifiState() == WifiManager.WIFI_STATE_ENABLED) {
			return true;
		} else {
			return false;
		}
	}

	private InetAddress intToInet(int value) {
		byte[] bytes = new byte[4];
		for (int i = 0; i < 4; i++) {
			bytes[i] = byteOfInt(value, i);
		}
		try {
			return InetAddress.getByAddress(bytes);
		} catch (UnknownHostException e) {
			// This only happens if the byte array has a bad length
			return null;
		}
	}

	private byte byteOfInt(int value, int which) {
		int shift = which * 8;
		return (byte) (value >> shift);
	}
}

抱歉!评论已关闭.