您的位置:首页 > 其它

获取手机ip地址工具类

2012-05-25 16:14 218 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: