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);
}
}