get Gateway Ip - Android android.net.wifi

Android examples for android.net.wifi:Wifi Property

Description

get Gateway Ip

Demo Code

import java.math.BigInteger;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteOrder;

import android.net.wifi.WifiManager;
import android.util.Log;

public class Main {

  public static String getGatewayIp(WifiManager w) {
    return ipAddressToString(w.getDhcpInfo().gateway);
  }/*from   w w w  .  java  2 s. co  m*/

  public static String ipAddressToString(int ipAddress) {

    if (ByteOrder.nativeOrder().equals(ByteOrder.LITTLE_ENDIAN)) {
      ipAddress = Integer.reverseBytes(ipAddress);
    }

    byte[] ipByteArray = BigInteger.valueOf(ipAddress).toByteArray();

    String ipAddressString;
    try {
      ipAddressString = InetAddress.getByAddress(ipByteArray).getHostAddress();
    } catch (UnknownHostException ex) {
      Log.e("WIFI_IP", "Unable to get host address.");
      ipAddressString = "NaN";
    }

    return ipAddressString;
  }

}

Related Tutorials