Skip to content

Instantly share code, notes, and snippets.

@shaobin0604
Created September 20, 2012 06:49
Show Gist options
  • Select an option

  • Save shaobin0604/3754310 to your computer and use it in GitHub Desktop.

Select an option

Save shaobin0604/3754310 to your computer and use it in GitHub Desktop.
public static byte[] getWifiHostAddress(Context context) {
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
DhcpInfo dhcp = wifiManager.getDhcpInfo();
int host = (dhcp.ipAddress & ~dhcp.netmask);
byte[] quads = new byte[4];
for (int k = 0; k < 4; k++) {
quads[k] = (byte) ((host >> k * 8) & 0xFF);
}
return quads;
}
public static String getWifiHostAddressBase64(Context context) {
byte[] address = getWifiHostAddress(context);
List<Byte> input = new ArrayList<Byte>();
for (byte segment : address) {
if (segment > 0) {
input.add(segment);
}
}
byte[] inputBytes = new byte[input.size()];
for (int i = 0; i < inputBytes.length; i++) {
inputBytes[i] = input.get(i);
}
return Base64.encodeToString(inputBytes, Base64.DEFAULT).trim();
}
public static int decodeWifiHostAddressBase64(String base64Str) {
byte[] bytes = Base64.decode(base64Str, Base64.DEFAULT);
Slog.d(Arrays.toString(bytes));
final int length = bytes.length;
int host = 0;
for (int i = 0; i < 4; i++) {
if (i < bytes.length) {
host = (host << 8) | bytes[length - i];
} else {
host = (host << 8);
}
}
return host;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment